73. 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.

Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

源码

void setZeroes(vector<vector<int>>& matrix) {
    if(matrix.size() < 1 || matrix[0].size() < 1) return;
    
    //标记第一行和第一列
    int firstLine = 1;
    int firstCol = 1;
   
    //用第一行、第一列标记是否清零
    for(int i = 0; i < matrix.size(); i++){
        for(int j = 0; j < matrix[0].size(); j++){
            if(matrix[i][j] == 0){
                if(i == 0) firstLine = 0;
                if(j == 0) firstCol = 0;
                
                matrix[0][j] = 0;
                matrix[i][0] = 0;
            }
        }
    }
    
    //清零
     for(int i = 1; i < matrix.size(); i++){
        for(int j = 1; j < matrix[0].size(); j++){
            if(matrix[i][0] == 0 || matrix[0][j] == 0){
                matrix[i][j] = 0;
            }
        }
    }
    
    if(firstCol == 0){
        for(int i = 0; i < matrix.size(); i++)
            matrix[i][0] = 0;
    }
    
    if(firstLine == 0){
        for(int i = 0; i < matrix[0].size(); i++)
            matrix[0][i] = 0;
    }

你可能感兴趣的:(73. Set Matrix Zeroes)