Skip to main content

Set Matrix Zeroes

Question

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

How can I modify a given m x n matrix so that if an element is 0, its entire row and column are set to 0 in-place?

Example 1
Input: 
[
[1,1,1],
[1,0,1],
[1,1,1]
]

Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]

Solution

all//Set Matrix Zeroes.py


class Solution:
def setZeroes(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
rows = len(matrix)
cols = len(matrix[0])

row_flags = [False] * rows
col_flags = [False] * cols

for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_flags[i] = True
col_flags[j] = True

for i in range(rows):
for j in range(cols):
if row_flags[i] or col_flags[j]:
matrix[i][j] = 0