01 Matrix – Solution & Complexity
Solution Walkthrough
Step 1: Start with the right graph view
- Treat every cell as a graph node with up to four neighbors.
- Running a separate shortest-path search from every
1works, but repeats almost the same exploration many times. - The key insight is to reverse the perspective: start BFS from all zero cells at once, so the first time you reach a cell is automatically its nearest-zero distance.
Step 2: Naive brute force: BFS from each 1-cell
- For every cell containing
1, launch a BFS until you touch a0. - That finds the correct nearest distance for that starting cell, because BFS explores in increasing path length order.
- But doing this independently for many cells can degrade to
O((m*n)^2)time in the worst case.
- For every cell containing
Step 3: Improve it with multi-source BFS
- Instead of asking every
1where its closest0is, let every0spread outward simultaneously. - Put all zero cells into the queue with distance
0before the BFS starts. - Then each unvisited neighbor gets distance
current + 1; because BFS expands by layers, the first assigned distance is the minimum one.
- Instead of asking every
Step 4: Optimal solution: one BFS from all zeros
- Initialize a distance matrix with
-1to mean unvisited. - Seed the queue with every zero cell and mark those distances as
0. - Pop cells in BFS order and assign each unseen neighbor its distance exactly once.
- Initialize a distance matrix with
Step 5: Dry run on `[[0,0,0],[0,1,0],[1,1,1]]`
Start with every zero already in the queue:
BFS layer Newly confirmed cells Distance matrix state initial all zeros: (0,0),(0,1),(0,2),(1,0),(1,2)[[0,0,0],[0,-1,0],[-1,-1,-1]]distance 1 (1,1),(2,0),(2,2)[[0,0,0],[0,1,0],[1,-1,1]]distance 2 (2,1)[[0,0,0],[0,1,0],[1,2,1]]The BFS layers stop there, and the final matrix is
[[0,0,0],[0,1,0],[1,2,1]].Step 6: Common mistakes
- Running a separate BFS from each
1in the final solution, which is correct but too slow compared with multi-source BFS. - Forgetting to enqueue all zero cells initially, which breaks the nearest-distance guarantee.
- Not marking neighbors as visited when enqueuing them, causing duplicate work or overwritten distances.
- Mixing up the four direction deltas or stepping diagonally by accident.
- Running a separate BFS from each
Step 7: Edge cases to test mentally
- A matrix that is already all zeros should be returned unchanged.
- A
1x1matrix containing0returns[[0]]. - Single-row and single-column matrices still work because BFS only uses valid neighbors.
- Multiple zeros on different edges should all contribute as simultaneous BFS sources.
Step 8: Final full solution and complexity
Seed the queue with every zero and run one multi-source BFS over the grid. Each cell is enqueued and processed at most once, so the time complexity is
O(m*n)and the extra space isO(m*n)for the queue plus distance/visited storage.