Given an m x n binary matrix mat, return a matrix of the same size where each cell holds the distance to the nearest 0. The distance between two adjacent cells is 1 (4-directional).
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given an m x n binary matrix mat, return a matrix of the same size where each cell holds the distance to the nearest 0. The distance between two adjacent cells is 1 (4-directional).
A medium graphs problem, graded against 6 test cases (4 of them hidden).
Nodes and edges - traversal, connectivity, cycles, and shortest paths.
Reach for it when you see: Explicit edges, a grid treated as a graph, or dependencies between items.
More Graphs problems →Multi-source BFS. Initialize the distance of every `0` to 0 and enqueue them. BFS outward; the first time a `1`-cell is reached gives its minimum distance.
Time: O(m·n). Space: O(m·n).
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.