<h3><a title="题目描述" href="https://leetcode-cn.com/problems/set-matrix-zeroes/">题目描述</a></h3>
![image.png](https://i.loli.net/2020/02/22/LV79oJgSDMHlis2.png)
<h4>我的解法</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="python">class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
columnlist = []
rawlist = []
for i in range(len(matrix)):
for k in range(len(matrix[i])):
if(matrix[i][k]==0):
rawlist.append(i)
if(k not in columnlist):
columnlist.append(k)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i in rawlist or j in columnlist:
matrix[i][j] = 0
</pre>
<p> </p>
<h4>更妙的解法</h4>
关键思想:
用matrix第一行和第一列记录该行该列是否有0,作为标志位
但是对于第一行,和第一列要设置一个标志位,为了防止自己这一行(一列)也有0的情况.注释写在代码里,直接看代码很好理解!
<pre class="EnlighterJSRAW" data-enlighter-language="python">class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row = len(matrix)
col = len(matrix[0])
row0_flag = False
col0_flag = False
# 找第一行是否有0
for j in range(col):
if matrix[0][j] == 0:
row0_flag = True
break
# 第一列是否有0
for i in range(row):
if matrix[i][0] == 0:
col0_flag = True
break
# 把第一行或者第一列作为 标志位
for i in range(1, row):
for j in range(1, col):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
#print(matrix)
# 置0
for i in range(1, row):
for j in range(1, col):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if row0_flag:
for j in range(col):
matrix[0][j] = 0
if col0_flag:
for i in range(row):
matrix[i][0] = 0
</pre>
<p> </p>
</ul>
Leetcode73 矩阵置零