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

 1 0 1 1 1 1 1 1 1

Then the output will be −

 0 0 0 1 0 1 1 0 1

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)
flag = False
if matrix == 0:
flag = True
row = False
column = False
for i in range(1,n):
if matrix[i] == 0:
column = True
break
for i in range(1,m):
if matrix[i] == 0:
row = True
break
for i in range(1,n):
for j in range(1,m):
if matrix[i][j] == 0:
matrix[j] = 0
matrix[i]=0
for i in range(1,n):
for j in range(1,m):
if not matrix[i] or not matrix[j]:
matrix[i][j] = 0
if flag:
for i in range(n):
matrix[i] = 0
for i in range(m):
matrix[i]=0
else:
if column:
for i in range(n):
matrix[i]=0
if row:
for i in range(m):
matrix[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]]