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:
Think out of the box!
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:
//本题的关键在于:必须先标记出哪些行哪些列全为0,再对其统一置0。如果不标记直接置0就会对其后的处理造成影响
//时间复杂度O(m*n),空间复杂度O(m+n)
void setZeroes(vector<vector<int>>& matrix) {
if(matrix.empty() || matrix[0].empty()) return;
int m = matrix.size();
int n = matrix[0].size();
//创建标记数组并初始化
bool *isRowZero = new bool[m];
bool *isColZero = new bool[n];
for(int i = 0; i < m; ++i) isRowZero[i] = false;
for(int i = 0; i < n; ++i) isColZero[i] = false;
//扫描矩阵,标记哪些行列需要置零
for(int i = 0 ; i < m; ++i){
for(int j = 0; j < n; ++j){
if(!matrix[i][j]){//本元素为0
isRowZero[i] = true;//标记本行需要为0
isColZero[j] = true;//标记本列需要为0
}
}
}
//扫描数组,根据标志数组,将需要置0的位置置0
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(isRowZero[i] || isColZero[j]) matrix[i][j] = 0;
}
}
//释放资源
delete []isRowZero;
delete []isColZero;
}
};
class Solution {
public:
//!!!借助第0行和第0列作为辅助存储标志某行某列是否全为0 AWOSOME!
//时间复杂度O(m*n), 空间复杂度O(1)
void setZeroes(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return;
int m = matrix.size();
int n = matrix[0].size();
bool isRowZero = false;
bool isColZero = false;
for (int i = 0; i < n; ++i){//先记录原始的第0行是否有0
if (!matrix[0][i]){
isRowZero = true;
break;
}
}
for (int i = 0; i < m; ++i){//先记录原始的第0列是否有0
if (!matrix[i][0]){
isColZero = true;
break;
}
}
for (int i = 1; i < m; ++i){//利用第0行和第0列标记某行和某列是否为全0
for (int j = 1; j < n; ++j){
if (!matrix[i][j]){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = 1; i < m; ++i){//根据标记处理矩阵(除第0行和第0列)
for (int j = 1; j < n; ++j){
if (!matrix[0][j] || !matrix[i][0]) matrix[i][j] = 0;
}
}
if (isRowZero){//处理第0行
for (int i = 0; i < n; ++i){//若原先第0行有0则第0行全为0
matrix[0][i] = 0;
}
}
if (isColZero){//处理第0列
for (int i = 0; i < m; ++i){//若原先第0列有0则第0列全为0
matrix[i][0] = 0;
}
}
}
};
Think out of the box!