You are given a grid mat of 0s and 1s with m rows and n columns. From any cell you can step up, down, left or right, and each step has length 1.
Return a grid of the same size where each cell holds the number of steps from that cell to the closest 0. A cell that is already 0 gets 0.
Example 1
Input: mat = [[0, 1, 1], [1, 1, 1], [1, 1, 0]] Output: [[0, 1, 2], [1, 2, 1], [2, 1, 0]] Why: the centre is two steps from either corner 0
2 more examples and the constraints
Example 2
Input: mat = [[1, 0], [1, 1]] Output: [[1, 0], [2, 1]] Why: the bottom-left cell needs two steps to reach the 0
Example 3
Input: mat = [[1, 1, 0, 1]] Output: [[2, 1, 0, 1]] Why: a single row: count the steps along it
Constraints
- 1 ≤ m, n and m × n ≤ 10,000
- Every cell is 0 or 1
- At least one cell is 0
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BFS from every 1O((m·n)²)
- Two passes of DPO(m·n)
- BFS from all 0s at onceO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 cells | Verdict |
|---|---|---|---|
| BFS from every 1 | O((m·n)²) | Correct, repeats work | |
| Two passes of DP | O(m·n) | Passes; no queue needed | |
| BFS from all 0s at once | O(m·n) | Best; one wave, easy to explain |
m = rows, n = columns.
Edge cases to test
- Only one 0. Every distance comes from that single cell; the wave spreads out from it alone.
- All 0s. Nothing to do: the output equals the input.
- A single row or column. [[1, 1, 0, 1]] gives [[2, 1, 0, 1]]; the code must not assume two dimensions of size more than 1.
- A 1 surrounded by 1s. Its distance is more than 1, so a plain check of the four neighbours is not enough.
Common mistakes
- Starting a BFS from each 1 instead of from all 0s at once, which is far too slow.
- Marking a cell visited when it is popped instead of when it is pushed, so it is pushed several times.
- Doing only the top-left pass of the DP, which misses zeros below or to the right.
How to talk through it
- 1Clarify. Only up, down, left and right moves? Is there always at least one 0?
- 2Give the brute force. A BFS from every 1 finds its nearest 0, but repeats the same work for each cell.
- 3Reverse the search. Start from all 0s at once: one BFS answers every cell in O(m·n).
- 4Code it. Push all zeros first, use the distance grid as the visited set.
- 5Test out loud. Run a grid with a single 0 in a corner and a 1 boxed in by 1s.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?