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?
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int m = matrix.size(),n = matrix[0].size();
vector<bool> col(n,false);
vector<bool> row(m,false);
for(int i = 0;i < m;i ++){
for(int j = 0;j < n;j ++){
if(matrix[i][j] == 0){
col[j] = true;
row[i] = true;
}
}
}
for(int k = 0;k < m;k ++){
if(row[k] == true){
for(int q = 0;q < n;q ++)
matrix[k][q] = 0;
}
}
for(int k = 0;k < n;k ++){
if(col[k] == true){
for(int q = 0;q < m;q ++)
matrix[q][k] = 0;
}
}
}
};
可使用第一行,第一列存储标记值,降低空间复杂度
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int m = matrix.size(),n = matrix[0].size();
bool isColZero = false;
bool isRowZero = false;
for(int i = 0;i < n;i ++){
if(matrix[0][i] == 0){
isColZero = true;
break;
}
}
for(int i = 0;i < m;i ++){
if(matrix[i][0] == 0){
isRowZero = true;
break;
}
}
for(int i = 0;i < m;i ++){
for(int j = 0;j < n;j ++){
if(matrix[i][j] == 0){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1;i < m;i ++){
for(int j = 1;j < n;j ++){
if(matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
}
if(isRowZero == true){
for(int q = 0;q < m;q ++)
matrix[q][0] = 0;
}
if(isColZero == true){
for(int q = 0;q < n;q ++)
matrix[0][q] = 0;
}
}
};