A more easy to understand solution than top solution from @mzchen


  • 1
    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            int col_check = 1, row_check = 1, rows=matrix.size(), cols=matrix[0].size();
           
            for(int i=0; i<rows; i++)  if(matrix[i][0]==0)  col_check=0;
            for(int i=0; i<cols; i++)  if(matrix[0][i]==0)  row_check=0;
            
            for(int i=1; i<rows; i++){
                for(int j=1; j<cols; j++){
                    if(matrix[i][j]==0)  matrix[i][0]=matrix[0][j]=0;
                }
            }
            
            for(int i=1; i<rows; i++){
                for(int j=1; j<cols; j++){
                    if(matrix[i][0]==0 || matrix[0][j]==0) matrix[i][j]=0;
                }
            }
            
            if(col_check==0)  { for(int i=0; i<rows; i++)  matrix[i][0]=0; }
            if(row_check==0)  { for(int i=0; i<cols; i++)  matrix[0][i]=0; }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.