题目描述
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?
解题思路
遍历第一遍,使用第一行和第一列用来标记该行或者列是否需要被设置为0。
再遍历一遍,根据上一次的标记,更新相应的行或者列。
由于第一行和第一列会在第一次遍历时会被新的标记所破坏,所以需要使用两个辅助变量,用来记录第一行和第一列是否需要全部置为0。
AC代码
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(); if (!m) return;
int n = matrix[0].size(); if (!n) return;
bool isRowZero = false;
bool isColZero = false;
// mark row and column
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
if (i == 0) isRowZero = true;
if (j == 0) isColZero = true;
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// set up row as zero
for (int i = 1; i < m; ++i) {
if (matrix[i][0] == 0) {
for (int j = 1; j < n; ++j)
matrix[i][j] = 0;
}
}
// set up column as zero
for (int j = 1; j < n; ++j) {
if (matrix[0][j] == 0) {
for (int i = 1; i < m; ++i) {
matrix[i][j] = 0;
}
}
}
if (isRowZero) {
for (int j = 0; j < n; ++j)
matrix[0][j] = 0;
}
if (isColZero) {
for (int i = 0; i < m; ++i)
matrix[i][0] = 0;
}
}
};