Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

01 Matrix

LeetCode #542Medium
Distance to nearest 0 · multi-source BFS

Given a matrix of 0s and 1s, return a matrix of the same size where each cell holds the distance to the nearest 0, with distance measured between 4-directionally adjacent cells.

Asked atGoogleAmazon
step 1 / 12
3 × 3 · distance to nearest 0
0
0
0
0
·
0
·
·
·
queue · cells to expand
front →
(empty)
← back
Multi-source BFS from all zeros
1dist = grid; mark 1-cells unknown
2queue = all 0-cells // multi-source seed, distance 0
3ring = 0
4while queue not empty:
5 ring++
6 for each cell in this frontier:
7 for each unknown neighbour:
8 dist = ring; enqueue it
9 queue = next frontier
10return dist
state
  • cells9

line 1The 01-Matrix: replace every cell with its distance to the NEAREST 0 (moving up/down/left/right). A naive idea — run a BFS from each 1 — is wasteful. Instead, flip it around: do ONE BFS that starts from ALL the zeros at once. The wavefront from the zeros reaches each 1 in increasing distance, so the first time a 1 is touched, it is touched by its closest zero.