Problem description
There is a matrix of N * M, where the element is 0, and if it is 0, then the row and the column are set to 0. Space complexity required for O (1)
Problem analysis
At first glance this problem is really simple, there is not too much algorithm content.
If there is an O (M + N) space, then all of the columns and rows containing 0 can be stored. Then set the 0 individually.
Now the requirement is to use the space complexity of O (1), what should be handled?
Problem solving
- The elements of the scan (row >= 1 && column >= 1), if the element is 0, set the position corresponding to the first row and the first column to 0
- After the matrix is scanned, all 0 of the information is saved in the first row and the first column. This scans the first row and the first column and, if you encounter 0, sets the entire column or the entire row to 0.
Specific code:
voidSetzeroes ( vector<vector<int> >&matrix) {intn = matrix.size ();if(N <=0)return;intm = matrix[0].size ();BOOLFirstRowHas0 =false; for(inti =0; I < m; i++)if(matrix[0][i] = =0) FirstRowHas0 =true;BOOLFirstColumnHas0 =false; for(inti =0; I < n; i++)if(matrix[i][0] ==0) FirstColumnHas0 =true; for(inti =1; I < n; i++) for(intj =1; J < M; J + +)if(Matrix[i][j] = =0) matrix[0][J] = matrix[i][0] =0; for(inti =1; I < n; i++)if(matrix[i][0] ==0) { for(intj =0; J < M; J + +) Matrix[i][j] =0; } for(inti =1; I < m; i++)if(matrix[0][i] = =0) { for(intj =0; J < N; J + +) Matrix[j][i] =0; }if(FIRSTROWHAS0) for(inti =0; I < m; i++) matrix[0][i] =0;if(FIRSTCOLUMNHAS0) for(inti =0; I < n; i++) matrix[i][0] =0; }
N*m Matrix: Set Matrix zeroes