1 """
2 Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
3 Example 1:
4 Input:
5 [
6 [1,1,1],
7 [1,0,1],
8 [1,1,1]
9 ]
10 Output:
11 [
12 [1,0,1],
13 [0,0,0],
14 [1,0,1]
15 ]
16 Example 2:
17 Input:
18 [
19 [0,1,2,0],
20 [3,4,5,2],
21 [1,3,1,5]
22 ]
23 Output:
24 [
25 [0,0,0,0],
26 [0,4,5,0],
27 [0,3,1,0]
28 ]
29 """
30 """
31 自己的方法:一遍AC
32 空间复杂度为O(m*n),需要进一步优化
33 """
34 class Solution:
35 def setZeroes(self, matrix):
36 """
37 Do not return anything, modify matrix in-place instead.
38 """
39 queue = set()
40 for i in range(len(matrix)):
41 for j in range(len(matrix[0])):
42 if matrix[i][j] == 0:
43 queue.add((i, j))
44 for x, y in queue:
45 for n in range(len(matrix[x])):
46 matrix[x][n] = 0
47 for m in range(len(matrix)):
48 matrix[m][y] = 0
49 """
50 解法二:自己优化了一下
51 """
52 class Solution2:
53 def setZeroes(self, matrix):
54 """
55 Do not return anything, modify matrix in-place instead.
56 """
57 row = set()
58 col = set()
59 for i in range(len(matrix)):
60 for j in range(len(matrix[0])):
61 if matrix[i][j] == 0:
62 row.add(i)
63 col.add(j)
64 for x in row:
65 matrix[x] = [0]*len(matrix[x])
66 for y in col:
67 for i in range(len(matrix)):
68 matrix[i][y] = 0
69 """
70 解法三:空间复杂度最低
71 将需要改变的值先变为'a'
72 最后再遍历一遍将值为'a'的变为0
73 """
74 class Solution3:
75 def setZeroes(self, matrix):
76 """
77 Do not return anything, modify matrix in-place instead.
78 """
79 row = len(matrix)
80 col = len(matrix[0])
81 for i in range(row):
82 for j in range(col):
83 if matrix[i][j] == 0:
84 for temp in range(row):
85 if matrix[temp][j] != 0:
86 matrix[temp][j] = 'a'
87 for temp in range(col):
88 if matrix[i][temp] != 0:
89 matrix[i][temp] = 'a'
90 for i in range(row):
91 for j in range(col):
92 if matrix[i][j] == 'a':
93 matrix[i][j] = 0