Set Matrix Zeroes in Python: Markers List Grid Demo
Given a matrix, this code finds all rows and columns that contain a zero and sets every element in those rows and columns to zero, using boolean marker arrays.
Python code
35 linesdef set_zeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_markers = [False] * rows
col_markers = [False] * cols
# First pass: record which rows and columns contain zeros
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_markers[i] = True
col_markers[j] = True
# Second pass: set zeros based on markers
for i in range(rows):
for j in range(cols):
if row_markers[i] or col_markers[j]:
matrix[i][j] = 0
return matrix
if __name__ == "__main__":
grid = [
[1, 2, 3],
[4, 0, 6],
[7, 8, 9]
]
print("Original grid:")
for row in grid:
print(row)
result = set_zeroes(grid)
print("\nAfter setting zeroes:")
for row in result:
print(row)
Output
Original grid:
[1, 2, 3]
[4, 0, 6]
[7, 8, 9]
After setting zeroes:
[1, 0, 3]
[0, 0, 0]
[7, 0, 9]
How it works
The algorithm uses two boolean arrays, row_markers and col_markers, to track which rows and columns contain at least one zero. First pass scans the entire matrix and flips the markers when a zero is found. Second pass iterates again and sets a cell to zero if either its row or column is marked. This approach avoids modifying the matrix during the first pass, preventing false positives from newly set zeros.
Common mistakes
- Modifying the matrix in the first pass, which can cause all cells to become zero due to cascading effects
- Forgetting to handle a 0x0 or 1x1 matrix edge case
- Using a single marker for both rows and columns incorrectly
Variations
- Use sets to keep track of rows and columns with zeros instead of boolean arrays
- Optimize to O(1) space by using the first row and first column as markers
Real-world use cases
- In image processing, zero out entire rows and columns of pixels where a defective pixel is detected.
- In spreadsheet or database applications, clear all cells in rows and columns that contain a placeholder zero.
- In game development, reset a board or grid to zero in entire lines that contain a zero value.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.