progress

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

Distance to nearest zero

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

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, with a single zero or thousands of them.

⭐ Bonus: speed tests on large grids earn a star in O(rows·cols). A search per cell, or a scan over every zero per cell, is too slow for them.

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