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.

Time Complexity
O(mn)
Space Complexity
O(1)

思路

If we need to set the whole row and col as 0, we just need first row and first col to know which row and col should be all set 0. But we will have a problem is we can't make sure that if the original first row or col has 0. So we use two boolean, one represents if the first row has 0, another represents if the first col has 0. If there is, set the boolean as true.

Then traverse the matrix except the first row and first col, if the same row or col at first row or col has 0. Set the whole row and col as 0.

Then check the two boolean, if there is true, set the row or col as 0.

代码

public void setZeroes(int[][] matrix) {
    //corner case
    if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return;
    boolean fr = false, fc = false;
    
    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[0].length; j++){
            if(matrix[i][j] == 0){
                if(i == 0) fr = true;
                if(j == 0) fc = true;
                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(fr){
        for(int j = 0; j < matrix[0].length; j++){
            matrix[0][j] = 0;
        }
    }
    if(fc){
        for(int i = 0; i < matrix.length; i++){
            matrix[i][0] = 0;
        }
    }
}

annielulu
5 声望5 粉丝