Skip to content

Graph Playground

Draw walls on a grid, then compare BFS and DFS on the same maze

1. The playground

Drag on the grid to add or remove walls. S is the start, E is the end. Run BFS or DFS and watch the visited cells fill in; the yellow line is the path that the search found. BFS guarantees the shortest path in this unweighted grid; DFS does not.

2. What to notice

  • BFS spreads outward in rings. The first time it reaches a cell is by a shortest path, so the yellow route is the shortest one.
  • DFS follows one corridor to its end before backtracking. It may find a longer path, and the visited pattern looks like a snake rather than a ring.
  • Both mark a cell visited when it is discovered, not when it is popped. That is what prevents duplicate work and keeps the frontier finite.
  • If you wall off the end, both searches visit the reachable region and report no path. The visited count still tells you how much of the grid was reachable.

3. The algorithms behind it

The grid is an unweighted graph. BFS uses a queue; DFS uses a stack. Both run in O(V + E) on an adjacency list, which is O(rows × cols) for this grid.

Traversal cost

The parent array is what turns a traversal into a path. When a cell is discovered, the search records which cell discovered it; at the end, following parent pointers from E back to S reconstructs the route.

4. Related lessons

Site soundtrack