Depth-First Search
Depth-first search picks a neighbor and keeps going. Instead of spreading evenly like BFS, it follows one branch as far as it can, then backs out to the most recent fork and tries the next branch. A stack makes that order happen: the newest pending cell is the next one to be visited.
Draw a maze on the grid and watch DFS commit to a direction. It can find a route to E, but neither the fewest moves nor the lowest terrain cost is guaranteed. The grid uses an explicit stack and remembers cells when it adds them, so a cell is never added twice. It considers right, down, left, and up, pushing those neighbors in reverse so the right-hand branch is tried first. Movement is only in those four directions.
Use Draw to paint walls, erase cells, add terrain costing five, or move the endpoints. Play, Back, Next, and the step slider expose each visit and discovery. Try No route to see the algorithm exhaust its frontier instead of claiming a path exists. Route cost includes each destination cell, with no charge for the starting cell.
Open the node-and-edge demonstration below for the recursive version. Its Mode menu offers goal search, full traversal, and cycle detection; its visible stack is the active chain of recursive calls. DFS takes O(V + E) time and O(V) auxiliary space. The visualizer keeps extra snapshots for reverse stepping.
Explore Depth-First Search on a node-and-edge graph
A grid is one kind of graph. Try a connected graph, a general tree, or a binary tree to see the same traversal without the maze. These shapes are undirected and connected.
Use Mode to switch between goal search, full traversal, and cycle detection. The stack shows the active recursive calls; coral marks backtracking or a cycle.