⬅ Previous Topic
Reverse Each Word in a String - Optimal ApproachNext Topic ⮕
Rotate Matrix by 90 Degrees Clockwise⬅ Previous Topic
Reverse Each Word in a String - Optimal ApproachNext Topic ⮕
Rotate Matrix by 90 Degrees ClockwiseTopic Contents
Given a 2D matrix, your task is to modify it in-place such that if any cell in the matrix is 0, you set its entire row and column to 0.
This transformation must be done in-place, meaning you should not use extra space for a duplicate matrix. The challenge is to achieve this optimally, using constant space.
If the matrix is empty, it should remain unchanged.
mat
.mat[i][0] == 0
or mat[0][j] == 0
, set mat[i][j] = 0
.def set_zeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
first_col_zero = any(matrix[i][0] == 0 for i in range(rows))
for i in range(1, rows):
for j in range(1, cols):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(1, rows):
for j in range(1, cols):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if first_row_zero:
for j in range(cols):
matrix[0][j] = 0
if first_col_zero:
for i in range(rows):
matrix[i][0] = 0
return matrix
# Sample Input
mat = [[1,1,1],[1,0,1],[1,1,1]]
print("Updated Matrix:", set_zeroes(mat))
⬅ Previous Topic
Reverse Each Word in a String - Optimal ApproachNext Topic ⮕
Rotate Matrix by 90 Degrees ClockwiseYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.