|
| 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