Breadth-First Search
Easy
BFS in Graphs
Finding the Shortest Path in unweighted environments.
15 min
Solve on LeetCodeProblem Understanding
In Graph BFS, we want to traverse a graph layer-by-layer starting from a source node. Unlike trees, graphs can have cycles (A->B->A), disconnected components, and multiple paths to the same node.
Goal:
- Given an unweighted graph, find the shortest path (minimum edges) from
starttotarget. - Visit all nodes reachable from
start.
Algorithm Strategy
Using the Queue (FIFO) structure:
- Queue: Stores nodes to visit next. Initialize with
[start]. - Visited Set: Crucial! Marks nodes as 'seen' to prevent infinite loops in cycles. Add
starttovisitedimmediately. - Loop: While Queue is not empty:
- Dequeue node
U. - For every neighbor
VofU:- If
Vis not invisited, add it tovisitedand EnqueueV.
- If
- Dequeue node
This guarantees that we process nodes in order of their distance: Distance 0 (start), then Distance 1 (neighbors), then Distance 2, etc.
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 Template
- 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.
