Skip to content

Commit 11814ca

Browse files
committed
miguel soln to zero matrix 1.8
1 parent 8ad3fff commit 11814ca

File tree

1 file changed

+135
-0
lines changed

1 file changed

+135
-0
lines changed
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
"""
2+
Python version 3.7.0
3+
1.8 - Zero Matrix
4+
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0
5+
"""
6+
import unittest
7+
from typing import List
8+
9+
10+
def zero_matrix(matrix: List[List[int]]) -> List[List[int]]:
11+
"""
12+
zero_matrix will take in an MxN matrix and when a 0 element is found, the whole column and row
13+
will be set to 0.
14+
Runtime: O(M * N)
15+
Space Complexity: O(min(M, N))
16+
:param matrix: an MxN matrix. M is the number of rows, N is the number of columns
17+
:return: a zero-modified matrix
18+
"""
19+
M = len(matrix)
20+
N = len(matrix[0])
21+
22+
zeroed_rows = set()
23+
zeroed_cols = set()
24+
25+
for row in range(M):
26+
for col, num in enumerate(matrix[row]):
27+
if num != 0 or row in zeroed_rows or col in zeroed_cols:
28+
continue
29+
# otherwise, set row to 0 by looping through columns of current row
30+
for i in range(N):
31+
matrix[row][i] = 0
32+
# set column to 0 by looping through rows of current column
33+
for j in range(M):
34+
matrix[j][col] = 0
35+
# update zeroed row and col sets
36+
zeroed_cols.add(col)
37+
zeroed_rows.add(row)
38+
return matrix
39+
40+
41+
class TestZeroMatrixFunction(unittest.TestCase):
42+
43+
def setUp(self):
44+
self.cases = [
45+
(
46+
[
47+
[1, 2, 3, 4],
48+
[5, 6, 0, 8],
49+
[9, 10, 11, 12],
50+
[13, 14, 15, 16]
51+
],
52+
[
53+
[1, 2, 0, 4],
54+
[0, 0, 0, 0],
55+
[9, 10, 0, 12],
56+
[13, 14, 0, 16]
57+
]
58+
),
59+
(
60+
[
61+
[1, 2],
62+
[3, 4],
63+
[5, 6],
64+
[7, 8],
65+
[9, 0]
66+
],
67+
[
68+
[1, 0],
69+
[3, 0],
70+
[5, 0],
71+
[7, 0],
72+
[0, 0]
73+
],
74+
),
75+
(
76+
[
77+
[1, 2],
78+
[0, 4],
79+
[5, 6],
80+
[7, 8],
81+
[9, 0]
82+
],
83+
[
84+
[0, 0],
85+
[0, 0],
86+
[0, 0],
87+
[0, 0],
88+
[0, 0]
89+
]
90+
),
91+
(
92+
[
93+
[1, 2, 3, 4, 5, 6, 0, 8, 9],
94+
[9, 8, 7, 6, 5, 4, 3, 2, 1],
95+
],
96+
[
97+
[0, 0, 0, 0, 0, 0, 0, 0, 0],
98+
[9, 8, 7, 6, 5, 4, 0, 2, 1],
99+
]
100+
),
101+
(
102+
[
103+
[0]
104+
],
105+
[
106+
[0]
107+
]
108+
),
109+
(
110+
[
111+
[1]
112+
],
113+
[
114+
[1]
115+
]
116+
),
117+
(
118+
[
119+
[1, 2],
120+
[3, 4]
121+
],
122+
[
123+
[1, 2],
124+
[3, 4]
125+
]
126+
)
127+
]
128+
129+
def test_zero_matrix(self):
130+
for matrix, expected in self.cases:
131+
self.assertEqual(zero_matrix(matrix), expected, msg=(matrix, expected))
132+
133+
134+
if __name__ == '__main__':
135+
unittest.main()

0 commit comments

Comments
 (0)