Skip to content

Commit 4e58a77

Browse files
committed
- Set Matrix Zeroes DaleStudy#283
1 parent b59fce9 commit 4e58a77

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

set-matrix-zeroes/ayosecu.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(mn), m = len(matrix), n = len(matrix[0])
6+
- Space Complexity: O(1)
7+
"""
8+
def setZeroes(self, matrix: List[List[int]]) -> None:
9+
"""
10+
Do not return anything, modify matrix in-place instead.
11+
"""
12+
m = len(matrix)
13+
n = len(matrix[0])
14+
15+
# Update row and column with a flag (infinite) if the value is not zero
16+
def updateRowCol(i, j):
17+
for k in range(m):
18+
if matrix[k][j] != 0:
19+
matrix[k][j] = float("inf")
20+
for k in range(n):
21+
if matrix[i][k] != 0:
22+
matrix[i][k] = float("inf")
23+
24+
# Visit all and update row and column if the value is zero
25+
for i in range(m):
26+
for j in range(n):
27+
if matrix[i][j] == 0:
28+
updateRowCol(i, j)
29+
30+
# Update flagged data to zero
31+
for i in range(m):
32+
for j in range(n):
33+
if matrix[i][j] == float("inf"):
34+
matrix[i][j] = 0
35+
36+
tc = [
37+
([[1,1,1],[1,0,1],[1,1,1]], [[1,0,1],[0,0,0],[1,0,1]]),
38+
([[0,1,2,0],[3,4,5,2],[1,3,1,5]], [[0,0,0,0],[0,4,5,0],[0,3,1,0]])
39+
]
40+
41+
sol = Solution()
42+
for i, (m, e) in enumerate(tc, 1):
43+
sol.setZeroes(m)
44+
print(f"TC {i} is Passed!" if m == e else f"TC {i} is Failed! - Expected: {e}, Result: {m}")

0 commit comments

Comments
 (0)