Set Matrix Zeroes

Set Matrix Zeroes

O(1) Space Version - 92ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
if m == 0:
return
n = len(matrix[0])
row_zero = False
for i in range(m):
if matrix[i][0] == 0:
row_zero = True
col_zero = False
for j in range(n):
if matrix[0][j] == 0:
col_zero = True
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(1, m):
if matrix[i][0] == 0:
for j in range(1, n):
matrix[i][j] = 0
for j in range(1, n):
if matrix[0][j] == 0:
for i in range(1, m):
matrix[i][j] = 0
if col_zero:
for j in range(n):
matrix[0][j] = 0
if row_zero:
for i in range(m):
matrix[i][0] = 0

test code

1
2
3
4
5
6
In [23]: m = [[1,1,1],[1,0,1],[1,1,1]]
In [24]: s = Solution(); s.setZeroes(m)
In [25]: m
Out[25]: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]

leet code