Tag:leetcode array matrix algorithm algorithm
given a m x n matrix, if an element is 0, set it entire row and column to 0. Do it on place.
follow up:
Did Your 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 isn't the best solution.
could you devise a constant space solution?
My idea of solving the problem is as follows: Traversing the matrix, saving the row's information with the first element of each row (if 0 indicates that a row must be set to 0), the first element of each column holds the information for that column, and then it is set according to that information. Because the first line column common element matrix[0][0], so another set of two flags row0 and col0, respectively, whether the first row, the first column to 0.
My C + + code is implemented as follows:
void Setzeroes (Vector<vector<int> > &matrix) {int row0 = 1; for (int j = 0; J < matrix[0].size (); ++j) if (matrix[0][j] = = 0) {row0 = 0; Break } int col0 = 1; for (int i = 0; i < matrix.size (); ++i) if (matrix[i][0] = = 0) {col0 = 0; Break } for (int i = 1; i < matrix.size (), ++i) for (int j = 1; J < Matrix[i].size (); ++j) if (matrix I [j] = = 0) {matrix[i][0] = 0; MATRIX[0][J] = 0; } for (int i = 1; i < matrix.size (), ++i) if (matrix[i][0] = = 0) for (int j = 1; j < Matrix[i]. Size (); ++J) Matrix[i][j] = 0; for (int j = 1; J < Matrix[0].size (), ++j) if (matrix[0][j] = = 0) for (int i = 1; i < matrix.size ( ); ++i) Matrix[i][j] = 0; if (row0 = = 0) for (int j = 0; J < matrix[0].size (); ++j) matrix[0][j] = 0; if (col0 = = 0) for (int i = 0; i < matrix.size (); ++i) matrix[i][0] = 0;}
Matrix[0][0] can actually be used to hold the information of the first column element, so it only needs to add the first line of the element's flag:
void Setzeroes (Vector<vector<int> > &matrix) { int row0 = 1; for (int j = 0; J < matrix[0].size (); ++j) if (matrix[0][j] = = 0) { row0 = 0; break; } for (int i = 1; i < matrix.size (), ++i) for (int j = 0; J < matrix[i].size (); ++j) if (matrix[i][j] = = 0) { C9/>matrix[i][0] = 0; MATRIX[0][J] = 0; } for (int i = 1; i < matrix.size (), ++i) if (matrix[i][0] = = 0) for (int j = 1; J < Matrix[i].size (); ++j) C15/>MATRIX[I][J] = 0; for (int j = 0, J < matrix[0].size (); ++j) if (matrix[0][j] = = 0) for (int i = 1; i < matrix.size (); ++i) C19/>MATRIX[I][J] = 0; if (row0 = = 0) for (int j = 0; J < matrix[0].size (); ++j) matrix[0][j] = 0;}
Leetcode[array]: Set Matrix zeroes