~/problems / Graphs / BFS / multi-source BFS

Distance to nearest zero

medium ~25 min

Implement update_matrix(mat) -> list[list[int]].

mat is a grid of 0s and 1s with at least one 0. Return a new grid of the same shape where each cell holds the number of steps (up, down, left or right) from that cell to the closest 0. Zeros get 0.

update_matrix([
    [1, 1, 1],
    [1, 0, 1],
    [1, 1, 1],
])
# [[2, 1, 2],
#  [1, 0, 1],
#  [2, 1, 2]]

Grids go up to 150×150. There may be a single zero or thousands of them, so neither a search per cell nor a scan over every zero per cell is fast enough: aim for O(rows·cols).

Show hint

Instead of searching outward from each 1, search outward from the zeros, all of them at once.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc