from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
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))
# Mark zeros on first row and column
for i in range(1, rows):
for j in range(1, cols):
if matrix[i][j] == 0:
matrix[i][0] = 0 # mark row
matrix[0][j] = 0 # mark column
# Zero rows based on marks
for i in range(1, rows):
if matrix[i][0] == 0:
for j in range(cols):
matrix[i][j] = 0
# Zero columns based on marks
for j in range(1, cols):
if matrix[0][j] == 0:
for i in range(rows):
matrix[i][j] = 0
# Zero first row if needed
if first_row_zero:
for j in range(cols):
matrix[0][j] = 0
# Zero first column if needed
if first_col_zero:
for i in range(rows):
matrix[i][0] = 0
# Driver code
matrix = [
[1,1,1],
[1,0,1],
[1,1,1]
]
sol = Solution()
sol.setZeroes(matrix)
for row in matrix:
print(' '.join(str(x) for x in row))first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
Check if first row has any zero to handle separately later
first_col_zero = any(matrix[i][0] == 0 for i in range(rows))
Check if first column has any zero to handle separately later
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
Mark rows and columns to be zeroed by setting first cell in row and column to zero
for i in range(1, rows):
if matrix[i][0] == 0:
for j in range(cols):
matrix[i][j] = 0
Zero entire row if marked
for j in range(1, cols):
if matrix[0][j] == 0:
for i in range(rows):
matrix[i][j] = 0
Zero entire column if marked
if first_row_zero:
for j in range(cols):
matrix[0][j] = 0
Zero first row if originally had zero
if first_col_zero:
for i in range(rows):
matrix[i][0] = 0
Zero first column if originally had zero