Problem statement:
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?
Solutions:
In follow up, O(mn) and O(m+n) is not the best solution, I use O(n+1) space complexitiy to solve the problem.
First,
I set up an bool flat to indicate if current row is selected to reset to 0.
I set up an bool array to indicate if current col is selected to reset to 0.
Second, Set up a two-level loop to enumerate all element to pick the row index and col index
Third, reset all the element to 0.
1 void setZeroes(vector<vector<int>>& matrix) { 2 if(matrix.empty()){ 3 return; 4 } 5 6 bool row_reset = false; 7 vector<bool> col_reset(matrix[0].size(), false); 8 9 // row index to reset to 0 10 vector<int> row_idx; 11 // col index to reset to 0 12 vector<int> col_idx; 13 14 for(vector<int>::size_type ix = 0; ix < matrix.size(); ix++){ 15 row_reset = false; 16 for(vector<int>::size_type iy = 0; iy < matrix[0].size(); iy++){ 17 if(matrix[ix][iy] == 0){ 18 // current row is already selected to reset to 0 19 if(!row_reset){ 20 row_idx.push_back(ix); 21 // avoid duplicate push back 22 row_reset = true; 23 } 24 // current col is already selected to reset to 0 25 if(!col_reset[iy]){ 26 col_idx.push_back(iy); 27 // avoid duplicate push back 28 col_reset[iy] = true; 29 } 30 } 31 } 32 } 33 34 // reset selected row to 0 35 for(vector<int>::size_type ix = 0; ix < row_idx.size(); ix++){ 36 for(vector<int>::size_type iy = 0; iy < matrix[row_idx[ix]].size(); iy++){ 37 matrix[row_idx[ix]][iy] = 0; 38 } 39 } 40 // reset selected col to 0 41 for(vector<int>::size_type ix = 0; ix < col_idx.size(); ix++){ 42 for(vector<int>::size_type iy = 0; iy < matrix.size(); iy++){ 43 matrix[iy][col_idx[ix]] = 0; 44 } 45 } 46 return; 47 }