Set matrix Zeros
Q:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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 not the best solution.
Could you devise a constant space solution?
A: 一般用O(m+n)的额外空间记录需要set zero的行和列。
如果不能用额外空间,将需要set zero的行和列映射到第一行和第一列。
a[i][j] = 0-------------->a[0][j] = 0,a[i][0] = 0;
那么如果a[0][j] = 0,那么表示第j列需要set zero;
a[i][0] = 0, 那么表示第i行需要 set zero;
因此第一行和第一列原先是否包含0,需要提前记录:bfirstRow 和bfirstCol. 然后第一行和第一列set zero应该放在最后一步,避免覆盖记录的信息。
void setZeroes(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function if(matrix.empty()) return; int m = matrix.size(); int n = matrix[0].size(); bool bfirstRow = false; bool bfirstCol = false; int i,j; for(i=0;i<m;i++) { if(!matrix[i][0]) { bfirstCol = true; break; } } for(j=0;j<n;j++) { if(!matrix[0][j]) { bfirstRow = true; break; } } for(i=1;i<m;i++) { for(j=1;j<n;j++) { if(!matrix[i][j]) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for(i=1;i<m;i++) { if(!matrix[i][0]) { for(j=1;j<n;j++) matrix[i][j] = 0; } } for(j=1;j<n;j++) { if(!matrix[0][j]) { for(i=1;i<m;i++) matrix[i][j] = 0; } } if(bfirstRow) { for(j=0;j<n;j++) matrix[0][j] = 0; } if(bfirstCol) { for(i=0;i<m;i++) matrix[i][0] = 0; } }