- 输入:
- [
- [1,1,1],
- [1,0,1],
- [1,1,1]
- ]
- 输出:
- [
- [1,0,1],
- [0,0,0],
- [1,0,1]
- ]
-
-
-
- 输入:
- [
- [0,1,2,0],
- [3,4,5,2],
- [1,3,1,5]
- ]
- 输出:
- [
- [0,0,0,0],
- [0,4,5,0],
- [0,3,1,0]
- ]
- # 标记+循环
- class Solution:
- def setZeroes(self, matrix: List[List[int]]) -> None:
- m = len(matrix)
- n = len(matrix[0])
- ans = []
- for i in range(m):
- for j in range(n):
- if matrix[i][j] == 0:
- ans.append([i,j])
- for i in ans:
- row = i[0]
- col = i[1]
- matrix[row] = [0] * n
- for x in range(m):
- matrix[x][col] = 0
- # 标记+数组循环
- import numpy as np
- class Solution:
- def setZeroes(self, matrix: List[List[int]]) -> None:
- m = len(matrix)
- n = len(matrix[0])
- ans = []
- for i in range(m):
- for j in range(n):
- if matrix[i][j] == 0:
- ans.append([i,j])
- matrix_arr = np.array(matrix)
- for i in ans:
- row = i[0]
- col = i[1]
- matrix_arr[row, :] = [0] * n
- matrix_arr[:, col] = [0] * m
- matrix[:] = matrix_arr.tolist()
- # True 标记法
- class Solution:
- def setZeroes(self, matrix: List[List[int]]) -> None:
- m = len(matrix)
- row = [False] * m
- n = len(matrix[0])
- col = [False] * n
- for i in range(m):
- for j in range(n):
- if matrix[i][j] == 0:
- row[i] = col[j] = True
- for i in range(m):
- for j in range(n):
- if row[i] or col[j] is True:
- matrix[i][j] = 0
- # 原地标记
- class Solution:
- def setZeroes(self, matrix: List[List[int]]) -> None:
- m = len(matrix)
- n = len(matrix[0])
- flag_row = any(matrix[i][0] == 0 for i in range(m))
- flag_col = any(matrix[0][j] == 0 for j in range(n))
- for i in range(1, m):
- for j in range(1, n):
- if matrix[i][j] == 0:
- matrix[i][0] = matrix[0][j] = 0
- for i in range(1, m):
- for j in range(1, n):
- if matrix[i][0] == 0 or matrix[0][j] == 0:
- matrix[i][j] = 0
- if flag_row:
- for i in range(m):
- matrix[i][0] = 0
- if flag_col:
- for j in range(n):
- matrix[0][j] = 0