This problem can is solved easily if we is allowed to use more than O (1) space. For example, create a copy of the original matrix (O (MN)-space) or just record the row and column indexes (O (M + N)-space). Well, is there a O (1)-space solution? Yes, refer to this link:-)
The key idea was to record the rows and columns, the need to being set to zeroes directly in the matrix ( if (!ma TRIX[I][J]) matrix[i][0] = matrix[0][j] = 0; ). The code is rewritten as follows.
1 classSolution {2 Public:3 voidSetzeroes (vector<vector<int>>&matrix) {4 intm = Matrix.size (), n = matrix[0].size ();5 BOOLC0 =false;6 for(inti =0; I < m; i++) {7 if(!matrix[i][0]) C0 =true;8 for(intj =1; J < N; J + +)9 if(!matrix[i][j]) matrix[i][0] = matrix[0][J] =0;Ten } One for(inti = m-1; I >=0; i--) { A for(intj = N-1; J j--) - if(!matrix[i][0] || !matrix[0][J]) Matrix[i][j] =0; - if(C0) matrix[i][0] =0; the } - } -};
[Leetcode] Set Matrix Zeroes