Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on 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 is not the best solution.
Could you devise a constant space solution?
Idea: The first row and the first column are used to indicate the row, whether the column is full 0, but the first row, the first column whether full 0=> with two additional variables stored
classSolution { Public: voidSetzeroes (vector<vector<int> > &matrix) { if(Matrix.empty ())return; BOOLFirstlinezero =false; BOOLFirstcolumnzero =false; if(matrix[0][0]==0) {Firstlinezero=true; Firstcolumnzero=true; } // the first line for(inti =1; i<matrix[0].size (); i++) { if(matrix[0][i]!=0)Continue; Firstlinezero=true; Break; } //The first column for(inti =1; I<matrix.size (); i++) { if(matrix[i][0]!=0)Continue; Firstcolumnzero=true; Break; } for(inti =1; I < matrix.size (); i++) { for(intj =1; j<matrix[0].size (); J + +) { if(Matrix[i][j]! =0)Continue; matrix[i][0] =0; matrix[0][J] =0; } } for(inti =1; i<matrix[0].size (); i++) { if(matrix[0][i]!=0)Continue; for(intj =1; J<matrix.size (); J + +) {Matrix[j][i]=0; } } for(inti =1; I<matrix.size (); i++) { if(matrix[i][0]!=0)Continue; for(intj =1; j<matrix[0].size (); J + +) {Matrix[i][j]=0; } } if(Firstlinezero) { for(inti =0; i< matrix[0].size (); i++) {matrix[0][i] =0; } } if(Firstcolumnzero) { for(inti =0; i< matrix.size (); i++) {matrix[i][0] =0; } } }};
The Set Matrix zeroes? (Graph)