73. Set Matrix Zeroes

Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`‘s.

You must do it in place.

Example 1:

``````Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
``````

Example 2:

``````Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
``````

Constraints:

• `m == matrix.length`
• `n == matrix[0].length`
• `1 <= m, n <= 200`
• `-2^31 <= matrix[i][j] <= 2^31 - 1`

• A straightforward 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，则将各自的 flag 设置为 true
- 然后扫描除去第一行第一列的整个数组，如果有0，则将对应的第一行和第一列的数字赋0
- 再次遍历除去第一行第一列的整个数组，如果对应的第一行和第一列的数字有一个为0，则将当前值赋0
- 最后根据第一行第一列的 flag 来更新第一行第一列

``````class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
bool rowZero = false, colZero = false;
for (int i = 0; i < m; ++i) {
if (matrix[i][0] == 0) colZero = true;
}
for (int i = 0; i < n; ++i) {
if (matrix[0][i] == 0) rowZero = true;
}
for (int i = 1; i < m; ++i) {
for (int j = 1; 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[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
if (rowZero) {
for (int i = 0; i < n; ++i) matrix[0][i] = 0;
}
if (colZero) {
for (int i = 0; i < m; ++i) matrix[i][0] = 0;
}
}
};
``````

``````class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
bool colZero = false;
for (int i = 0; i < m; ++i) {
if (matrix[i][0] == 0) colZero = true;
for (int j = 1; j < n; ++j) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 1; --j) {
if (matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
if (colZero) matrix[i][0] = 0;
}
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/73

Game of Life

Number of Laser Beams in a Bank

Minimum Operations to Remove Adjacent Ones in Matrix

Remove All Ones With Row and Column Flips II

https://leetcode.com/problems/set-matrix-zeroes/

https://leetcode.com/problems/set-matrix-zeroes/solutions/26014/any-shorter-o-1-space-solution/

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation