题目链接:https://oj.leetcode.com/problems/set-matrix-zeroes/
题目内容:
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:
转载请注明作者:vanish_dust
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?
解题思路:没想到好的方法,就是最简单的O(m*n)。就是搜到一个0,就把行列都变为0,用了一个符号数组,识别是以前的0,还是变成的0.
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
size_t m = matrix.size();
size_t n = matrix[0].size();
int s[m][n];
for(size_t i = 0 ;i != m;i++)
for(size_t j = 0 ;j !=n;j++)
s[i][j] = 1;
for(size_t i = 0 ;i != m;i++)
for(size_t j = 0 ;j !=n;j++) {
if(matrix[i][j] == 0 && s[i][j] != -1) {
for(size_t k = 0; k != n;k++) {
if(matrix[i][k]!=0 )
s[i][k] = -1;
matrix[i][k] = 0;
}
for(size_t l = 0; l != m;l++) {
if(matrix[l][j]!=0 )
s[l][j] = -1;
matrix[l][j] = 0;
}
}
}
}
};
转载请注明作者:vanish_dust