## 73. Set Matrix Zeroes

Published on with 0 views and 0 comments

Given an `m x n` matrix. If an element is 0, set its entire row and column to 0. Do it in-place.

• A straight forward solution using O(m**n) 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?

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<sup>31</sup><span> </span><= matrix[i][j] <= 2<sup>31</sup><span> </span>- 1`

##### 代码

golang:

``````func setZeroes(matrix [][]int)  {
var row0IsZero bool

m := len(matrix)
n := len(matrix[0])

for i := 0; i < m; i++ {
if matrix[i][0] == 0 {
row0IsZero = true
}
// 从第二列开始扫，第一列用来记录是否需要刷成0
for j := 1; j < n; j++ {
if matrix[i][j] == 0 {
matrix[i][0] = 0
matrix[0][j] = 0
}
}
}

for i := m - 1; i >= 0; i-- {
for j := n - 1; j >= 1; j-- {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0
}
}

// 判断每行首位需不需要置为0
if row0IsZero {
matrix[i][0] = 0
}
}
}
``````