BFS & DFS Maze Explorer
Run breadth-first and depth-first search on the same maze grid, see ring-by-ring expansion versus deep dives, and the shortest path guarantee.
Run breadth-first and depth-first search on the same maze grid, see ring-by-ring expansion versus deep dives, and the shortest path guarantee.
step 1 / 101
What's happening
BFS starts at node 12. The queue drives the order: visit nearest neighbors first, neighbors-of-neighbors after that.
Run BFS first, then switch to DFS on the same maze: BFS expands ring by ring (its final path is shortest); DFS dives down one corridor at a time and simply reports the first route it stumbles onto.
Understand the algorithm
What it is
BFS explores a maze ring by ring from the start, guaranteeing the shortest path; DFS dives down one branch as deep as possible before backtracking.
Why it matters
They are the two fundamental graph traversals, and the maze makes their personality difference visible: BFS's patient ring expansion finds shortest paths, DFS's deep dive finds A path fast and cheap. Choosing between them is a daily decision in real systems.
How it works
- 1BFS: keep a FIFO queue of discovered cells; visit, enqueue all unvisited neighbors; repeat. The first time you reach the goal is provably via a shortest path.
- 2Reconstruct the path by following parent pointers backwards from the goal.
- 3DFS: keep a stack (or recursion); go as deep as possible along one branch, backtrack when stuck.
- 4Compare: same maze, same start and goal, the exploration order and final path differ dramatically.
Real-world uses
- BFS: GPS/navigation shortest routes, social-network 'degrees of separation', web crawlers level by level, puzzle minimum-move solvers
- DFS: maze generation, cycle detection, topological sort, connected-component identification, backtracking puzzles
Strengths
- BFS guarantees shortest paths in unweighted graphs
- DFS uses O(height) memory, tiny on wide, shallow graphs
- Both are O(V + E): each cell and wall processed once
Limitations
- BFS's queue can hold an entire frontier, O(width) memory on large grids
- DFS gives NO guarantee of shortest paths, 'a path' is not 'the path'
- Weighted graphs need Dijkstra, not either of these
Switch between BFS and DFS on identical mazes.