π BFS (Breadth-First Search)
You're navigating a city map. You want the shortest route from your location to the destination. BFS (Breadth-First Search) explores the map level by level, guaranteeing you find the shortest path in unweighted graphs!
The Navigation Problem
When traversing a graph, you need to visit all vertices systematically. BFS does this by exploring level by level:
Real-World BFS Applications
- GPS Navigation: Find shortest route (unweighted roads)
- Web Crawling: Crawl websites level by level
- Social Networks: Find people within K connections
- Puzzle Solving: Minimum moves to solve puzzle
- Network Broadcasting: Spread message level by level
How BFS Works
BFS Algorithm
- Start with source vertex, mark visited
- Add source to queue
- While queue not empty:
- Dequeue vertex
- Process vertex
- Enqueue all unvisited neighbors
Key insight: Queue (FIFO) ensures level-by-level exploration!
See BFS in Action
Why BFS Finds Shortest Path
The Guarantee
In unweighted graphs, BFS guarantees shortest path because:
- All vertices at distance 1 are visited before distance 2
- Queue ensures we process closer vertices first
- First time we reach a vertex = shortest path
Note: Only works for unweighted graphs! For weighted graphs, use Dijkstra's.
Implementation Details
1. Queue-Based
Why Queue?
Queue (FIFO - First In First Out) ensures:
- Level 0 vertices processed before level 1
- Level 1 before level 2, etc.
- Natural level-by-level order
2. Visited Tracking
Mark vertices as visited to avoid cycles and reprocessing.
3. Distance Tracking
Track distance from source to each vertex - useful for shortest path problems.
The Complete Code
Click Run to execute your code
BFS Applications
Common Use Cases
- Shortest Path: Unweighted graphs
- Level-order Traversal: Trees and graphs
- Connected Components: Find all components
- Web Crawling: Visit sites level by level
- Social Networks: Degrees of separation
- Bipartite Check: Two-coloring graphs
BFS vs DFS
Comparison
| Aspect | BFS | DFS |
|---|---|---|
| Data Structure | Queue (FIFO) | Stack/Recursion |
| Order | Level by level | Deep first |
| Shortest Path | Yes (unweighted) | No guarantee |
| Space | O(V) - stores level | O(V) - recursion depth |
Summary
What You've Learned
BFS is a fundamental graph traversal algorithm:
- Algorithm: Queue-based level-by-level traversal
- Time: O(V + E) - visit each vertex and edge once
- Space: O(V) - queue can hold all vertices at widest level
- Shortest Path: Guarantees shortest path in unweighted graphs
- Applications: GPS navigation, web crawling, level-order problems
- Key insight: Queue ensures closer vertices processed first
What's Next?
You've mastered BFS! Next, we'll explore DFS (Depth-First Search) - going deep into the graph before backtracking, perfect for maze solving, cycle detection, and topological sorting!
Enjoying these tutorials?