Why BFS finds the shortest way through a maze and DFS finds the first one.
About this comparison
Both searches start in the top left corner of the same 31 by 20 maze and look for the flag on its bottom edge. Depth-first search is the orange line, breadth-first search the blue water. Each counter shows the length, in steps, of the route that search is holding.
Depth-first search (DFS) follows one corridor as far as it goes, taking the first open way at every fork in a fixed order: north, east, south, west. Its path is a stack. At a dead end it backs up to the last fork with an untried way, so its counter climbs as it digs and drops as it backs out.
Breadth-first search (BFS) spreads in rings from a queue: every cell one step away, then two, and so on. The ring that first touches the flag gives the length of the shortest route.
DFS commits to a direction blind. BFS never commits: it holds every route of the same length at once. Both visit each cell at most once, O(V+E), which on a grid is O(R×C). What differs is the answer: DFS returns the first path it finds, BFS a shortest one when every step costs the same.
At the start DFS takes east, first in its order, along the top and away from the flag. It walks into 4 dead ends and backs out, 33 steps back in all, and once passes right by the flag, because west comes last. It arrives after 176 steps forward with a route of 143 steps. BFS goes down the left side and reaches the flag on its 39th ring: 39 steps, 3.7 times shorter.
The effort was close: DFS touched 177 cells, BFS had filled 157. The counters carry the result, not the finish order.
Use BFS for the fewest moves when every move costs the same: a maze, a game map, fire or flood spreading one cell per turn. If moves cost different amounts, use Dijkstra.
Use DFS when any route will do or you must visit everything: does the maze have an exit, how many islands, fill a region, find a cycle. Its stack holds only the current path; the BFS queue holds a whole ring.