题目链接: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.
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?
(1)思路:这道题最主要的是要求节省空间,降低空间复杂度到常数。那么就可以借助矩阵本身的空间,比如第一行和第一列来记录矩阵元素的0的情况。首先把第一行和第一列的元素检查一下,如果有0先记录下来但是不要对第一行和第一列处理。然后依次检查所有元素并处理,比如在第5行第6列找到了一个0,那么就把第一行第六列的元素变成0,同时把第五行第一列的元素变成0,检查完整个矩阵后根据第一行和第一列的0元素情况对矩阵进行整理,再把之前第一行和第一列的1情况还原回去。
(2)代码:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int row = matrix.size();
if(row == 0) return;
int col = matrix[0].size();
if(col == 0) return;
bool firstrowiszero = false;
bool firstcoliszero = false;
for(int j = 0; j < col; ++j)
if(matrix[0][j] == 0){
firstrowiszero = true;
break;
}
for(int i = 0; i < row; ++i)
if(matrix[i][0] == 0){
firstcoliszero = true;
break;
}
for(int i = 1; i < row; ++i)
for(int j = 1; j < col; ++j){
if(matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
for(int i = 1; i < row; ++i)
for(int j = 1; j < col; ++j)
if(matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if(firstrowiszero){
for(int j = 0; j < col; ++j)
matrix[0][j] = 0;
}
if(firstcoliszero){
for(int i = 0; i < row; ++i)
matrix[i][0] = 0;
}
}
};