Search This Blog

Friday, December 7, 2012

LeetCode: Set Matrix Zeroes


Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

public class Solution {
    public void setZeroes(int[][] matrix) {
   
        boolean firstRow=false, firstColumn=false;
        for(int i=0;i<matrix.length;i++){
            if(matrix[i][0]==0){
                firstColumn = true;
                break;
            }
        }
        
        for(int i=0;i<matrix[0].length;i++){
            if(matrix[0][i]==0){
                firstRow = true;
                break;
            }
        }
    
        for(int i=1;i<matrix.length;i++){
            for(int j=1;j<matrix[0].length;j++){
                if(matrix[i][j]==0){
                    matrix[i][0]=0;
                    matrix[0][j]=0;
                }
            }
        }
        
        for(int i=1;i<matrix.length;i++){
            for(int j=1;j<matrix[0].length;j++){
                if(matrix[i][0]==0||matrix[0][j]==0){
                    matrix[i][j]=0;
                }
            }
        }
        
        if(firstRow){
            for(int i=0;i<matrix[0].length;i++)
                matrix[0][i]=0;
        }
        
        if(firstColumn){
            for(int i=0;i<matrix.length;i++)
                matrix[i][0]=0;
        }
        
    }
}

2 comments:

TBlogger said...

请问可否这样做:
第一次扫描全matrix,如果遇到0就把该行该列设成2,注意这时如果该列/该行有别的元素是0,那不设成2,这样扫描一遍后,就知道凡是2或0的位置就要设成0
第二遍再把它们都设成0

谢谢

Anonymous said...

@Thomas Liu:
What if the original matrix containing 2s?