Program to convert each element in row and column to zero for zero values in Python

PythonServer Side ProgrammingProgramming

Suppose we have a 2D matrix of numbers, now for each zero in the given matrix and replace all values in its row and column with zero, and return the final matrix.

So, if the input is like matrix, then the output will be matrix as the 0th, 2nd and 3rd rows contain 0 and the final matrix contains 0 in those rows. Similarly 0th, 1st and 2nd columns contain 0 and the final matrix contains 0 in those columns.

To solve this, we will follow these steps:

n := row count, m := column count
res := make a matrix of size n x m and fill with 0
transpose := transpose given matrix
for each row i, do
   if 0 not in matrix[i], then
      for each column j in matrix, do
         if 0 not in transpose[j], then
            res[i, j] := matrix[i, j]
return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, matrix):
      n, m = len(matrix), len(matrix[0])
      res = [[0 for __ in range(m)] for _ in range(n)]
      transpose = [list(row) for row in zip(*matrix)]

      for i in range(n):
         if 0 not in matrix[i]:
            for j in range(m):
               if 0 not in transpose[j]:
                  res[i][j] = matrix[i][j]

      return res

ob = Solution()
matrix = [
      [6, 0, 0, 6, 9],
      [4, 9, 9, 4, 8],
      [0, 8, 3, 4, 2],
      [9, 0, 7, 8, 3],
      [5, 2, 9, 6, 8]
]
print(ob.solve(matrix))

Input

matrix = [ [6, 0, 0, 6, 9], [4, 9, 9, 4, 8], [0, 8, 3, 4, 2], [9, 0, 7, 8, 3], [5, 2, 9, 6, 8] ]

Output

[[0, 0, 0, 0, 0], [0, 0, 0, 4, 8], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 6, 8]]
raja
Updated on 09-Nov-2020 10:28:02

Advertisements