链接:http://leetcode.com/onlinejudge#question_73
原题:
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?
思路:这道题目关键是要求constant space solution,所以要转变记录状态的方法。
我是利用相邻两行做状体记录的。
1)判断下一行是否有0,如果有的话,那么处理改行时候,要把所有非0值置为0;
2)把当前行有0的列,在下一行对应的列那个值也置为0。
3)最后处理最后一行,把有0的列,都全部置为0
时间为O(m*n), 空间复杂度为O(1)
代码:
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (matrix.size() == 0)
return;
int rows = matrix.size();
int cols = matrix[0].size();
bool nextFlag = existZeroInRow(matrix, 0);
int i = 0;
for ( ; i<rows-1; i++) {
bool curFlag = nextFlag;
nextFlag = existZeroInRow(matrix, i+1);
for (int j=0; j<cols; j++) {
if (matrix[i][j] != 0 && curFlag) {
matrix[i][j] = 0;
} else if (matrix[i][j] == 0) {
matrix[i+1][j] = 0;
}
}
}
//process the last raw
for (int j=0; j<cols; j++) {
if (matrix[i][j] != 0 && nextFlag) {
matrix[i][j] = 0;
} else if (matrix[i][j] == 0) {
for (int n=0; n<=i; n++)
matrix[n][j] = 0;
}
}
}
private:
bool existZeroInRow(const vector<vector<int> > &matrix, int row) {
int cols = matrix[row].size();
for (int i=0; i<cols; i++) {
if (matrix[row][i] == 0)
return true;
}
return false;
}
};