Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 44fc985

Browse files
Create setMatrixZero.py
1 parent cac6a84 commit 44fc985

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎DSA-master/Day-1/setMatrixZero.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Set Matrix Zero
2+
# Problem Statement: Given a matrix if an element in the matrix is 0
3+
# then you will have to set its entire column and row to 0 and then
4+
# return the matrix.
5+
6+
# Input: matrix=[[1,1,1],[1,0,1],[1,1,1]]
7+
# Output: [[1,0,1],[0,0,0],[1,0,1]]
8+
9+
def getZeros(matrix, shape):
10+
"""
11+
returns the location of zeros in the matrix
12+
as a list of tuples
13+
Time Complexity: O(M*N) where MxN is the shape of matrix
14+
"""
15+
r,c = shape
16+
zeros = []
17+
for i in range(0,r):
18+
for j in range(0,c):
19+
if matrix[i][j] == 0:
20+
zeros.append((i,j))
21+
return zeros
22+
23+
def setZeros(matrix, shape, zeros):
24+
"""
25+
returns the modified matrix
26+
Time complexity: O(M+N) where MxN is the shape of the matrix
27+
"""
28+
r,c = shape
29+
30+
for z in zeros:
31+
m,n = z
32+
for i in range(0,r):
33+
matrix[i][n] = 0
34+
35+
for j in range(0,c):
36+
matrix[m][j] = 0
37+
38+
return matrix
39+
40+
41+
42+
M = [[1,1,1],[1,0,1],[1,1,1]]
43+
print(M)
44+
res = getZeros(M, (3,3))
45+
print(res)
46+
sol = setZeros(M, (3,3), res)
47+
print(sol)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /