Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.
Click to show follow up.
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?
It is said that the problem is careercup on the original problem, I have not brushed careercup, so do not know, but this is not difficult, although I also read the solution on the internet according to write, but the next encounter absolutely want to rise. This problem is said in the space complexity of O (MN) solution from needless to say, directly create a matrix and other matrices, and then a row of the sweep, as long as there are 0, the new matrix will be the corresponding line full 0, line sweep and then sweep the column, and then the updated matrix assigned to the matrix can be, The spatial complexity of this algorithm is too high. It is optimized to O (m+n) by using a one-dimensional array of length m to record whether there are 0 in each row, using a one-dimensional array of length n to record whether there are 0 in each column, and finally updating the matrix array directly. The requirement of this problem is to use O (1) space, then we can not create a new array, we consider using the first row of the original array of the first column to record the rows of each column is 0.
-Scan first Column first, if 0, set the respective flag to True
-then the scan removes the entire array of the first column of the first row, and if there is 0, assigns the number of the first row and the first column 0
-Iterate over the entire array that removes the first column of the first row, if the corresponding first row and the first column have a number of 0, the current value is assigned 0
-finally update the first row first column according to the first row of flag
The code is as follows:
classSolution { Public: voidSetzeroes (vector<vector<int> > &matrix) { if(Matrix.empty () | | matrix[0].empty ())return; intm = Matrix.size (), n = matrix[0].size (); BOOLRowzero =false, Colzero =false; for(inti =0; I < m; ++i) {if(matrix[i][0] ==0) Colzero =true; } for(inti =0; I < n; ++i) {if(matrix[0][i] = =0) Rowzero =true; } for(inti =1; I < m; ++i) { for(intj =1; J < N; ++j) {if(Matrix[i][j] = =0) {matrix[0][J] =0; matrix[i][0] =0; } } } for(inti =1; I < m; ++i) { for(intj =1; J < N; ++j) {if(matrix[0][J] = =0|| matrix[i][0] ==0) {Matrix[i][j]=0; } } } if(Rowzero) { for(inti =0; I < n; ++i) matrix[0][i] =0; } if(Colzero) { for(inti =0; I < m; ++i) matrix[i][0] =0; } }};
[Leetcode] Set Matrix Zeroes matrix assignment 0