Algorithm Steps
- Given a 2D matrix
mat
. - Use the first row and first column as markers to indicate if a row or column should be set to zero.
- Check if the first row and first column themselves contain any zero using two separate flags.
- Traverse the rest of the matrix:
- → If any element is 0, mark its row and column in the first row and column.
- Traverse the matrix again (excluding first row and column):
- → If
mat[i][0] == 0
ormat[0][j] == 0
, setmat[i][j] = 0
. - Finally, update the first row and first column based on the flags.
Set Matrix Zeroes Using Constant Space Code
Python
JavaScript
Java
C++
C
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))