ChoralSoft Learn

Breadth-first versus depth-first search

Two ways to explore a graph, and why one of them always finds the shortest path.

Breadth-first versus depth-first search

Find a route from the blue start square to the red goal. Click any square to toggle a wall, then run each algorithm and compare how many squares it explores and how long its path is.

Choose an algorithm to begin.

What to notice: BFS spreads out evenly like a ripple, so the first time it reaches the goal it has found a shortest path. DFS dives down one corridor before backing up, so its path can be much longer even when it explores fewer squares.

Go deeper

More explainers: Learn hub · Printable cheat sheets · Learning paths