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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

35 lines
Python 3.9+
def 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

stdout
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

  1. Use sets to keep track of rows and columns with zeros instead of boolean arrays
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.