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?
Test instructions: Set the row of 0 to 0.
Idea: In order not to open extra space, we use the first row and the first column, and then determine whether the first row, column also to set 0
Class Solution {Public:void setzeroes (vector<vector<int> > &matrix) {int n = matrix.size (); int m = Matrix [0].size (); bool FirstRow = false, Firstcol = false;for (int i = 0; i < n; i++) if (matrix[i][0] = = 0) {Firstcol = true; break;} for (int i = 0; i < m; i++) if (matrix[0][i] = = 0) {firstrow = True;break;} for (int i = 1, i < n; i++) {for (int j = 1; j < M; J + +) {if (matrix[i][j] = = 0) {Matrix[i][0] = 0;matrix[0][j] = 0; }}}for (int i = 1; i < n; i++) {if (matrix[i][0] = = 0) for (int j = 1; j < M; j + +) Matrix[i][j] = 0;} for (int i = 1, i < m; i++) {if (matrix[0][i] = = 0) for (int j = 1; j < N; j + +) Matrix[j][i] = 0;} if (firstrow) {for (int i = 0; i < m; i++) matrix[0][i] = 0;} if (Firstcol) {for (int i = 0; i < n; i++) matrix[i][0] = 0;}};
Leetcode Set Matrix Zeroes