Set Matrix Zeroes in Python

PythonServer Side ProgrammingProgramming

Consider we have a matrix, in that matrix if one element is 0, then make the entire row and column of that matrix to 0. The conversion will be in-place. So if the matrix is −

101
111
111

Then the output will be −

000
101
101

Let us see the steps −

  • n := number of rows, m := number of columns, set flag := false
  • if mat[0, 0] = 0, then set flag := true
  • set row := false, and col := false
  • for i in range 1 to n
    • if mat[i, 0] = 0, then set col := True and break the loop
  • for i in range 1 to m
    • if mat[0, i] = 0, then set row := True and break the loop
  • for i in range 1 to n
    • for j in range 1 to m
      • if mat[i, j] = 0, then set mat[i, 0] = 0 and mat[0, j] := 0
  • for i in range 1 to n
    • for j in range 1 to m
      • if mat[i, 0] = 0 and mat[0, j] = 0, then set mat[i, j] = 0
  • if flag is set
    • for i in range 0 to n, mat [i, 0] := 0
    • for i in range 0 to m, mat[0, i] := 0
  • otherwise
    • if col is set, then for i in range 0 to n, mat [i, 0] := 0
    • if row is set, then for i in range 0 to m, mat [0, i] := 0

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def setZeroes(self, matrix):
      n = len(matrix)
      m = len(matrix[0])
      flag = False
      if matrix[0][0] == 0:
         flag = True
         row = False
         column = False
      for i in range(1,n):
         if matrix[i][0] == 0:
            column = True
            break
      for i in range(1,m):
         if matrix[0][i] == 0:
            row = True
            break
      for i in range(1,n):
         for j in range(1,m):
            if matrix[i][j] == 0:
               matrix[0][j] = 0
               matrix[i][0]=0
      for i in range(1,n):
         for j in range(1,m):
            if not matrix[i][0] or not matrix[0][j]:
               matrix[i][j] = 0
      if flag:
         for i in range(n):
            matrix[i][0] = 0
         for i in range(m):
            matrix[0][i]=0
      else:
         if column:
            for i in range(n):
               matrix[i][0]=0
         if row:
            for i in range(m):
               matrix[0][i]=0
      return matrix
ob1 = Solution()
print(ob1.setZeroes([[1,0,1],[1,1,1],[1,1,1]]))

Input

[[1,0,1],[1,1,1],[1,1,1]]

Output

[[0, 0, 0], [1, 0, 1], [1, 0, 1]]
raja
Published on 03-Feb-2020 14:29:00
Advertisements