Breadth-First Search
Medium
01 Matrix
Find the distance of the nearest 0 for each cell.
20 min
Solve on LeetCodeProblem Understanding
Given an m x n binary matrix:
- 0: A goal cell.
- 1: An empty cell.
For each cell, find the distance to the nearest 0. The distance between adjacent cells is 1.
Algorithm Strategy
A naive BFS from each 1 would be too slow (O((RC)^2)).
Better Approach: Multi-Source BFS
- Reverse Thinking: Instead of finding nearest
0from1s, let the0s expand outward like a flood. - Initialization:
- Enqueue ALL cells containing
0attime=0. - Mark all
1cells asInfinity(unvisited).
- Enqueue ALL cells containing
- Expansion: Pop a cell. Visit its unvisited neighbors. Set neighbor dist =
current dist + 1. Enqueue neighbor.
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution Code
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
