Watch Depth-First Search (DFS) find paths through complex grids. Interactive matrix explorations.
About this algorithm
Grid DFS explores a grid by heading one way until it is blocked, then backing up to the last cell that still has an unexplored side. It tells you whether the target can be reached at all and visits every cell connected to the start, but the route it returns is usually far longer than the shortest one.
Use grid DFS for reachability and for labelling regions: counting islands, filling an area the way a paint bucket tool does, or checking that a maze has an exit. It needs nothing more than a stack or a recursive call, and for those tasks the order of visits makes no difference. Pick grid BFS when the number of steps matters, because BFS returns a shortest route and DFS returns whatever route its direction order happens to find.
Put the start cell on a stack and mark it visited.
Take the cell off the top of the stack. If it is the target, stop.
Check the four side neighbours in the order right, down, left, up. Push each one that is on the grid, not a wall and not yet visited, marking it visited and remembering where it came from. Up is pushed last, so it is popped first: the search keeps heading up until it hits the edge or a wall.
When a cell has no open neighbours, nothing new is pushed and the next pop is an older cell somewhere back along the way. The run ends at the target, or when the stack is empty, which means the target is walled off.
Your board is random, so take the board from the BFS page: 5 rows and 7 columns, no walls, start at (2, 3) and target at (4, 0). DFS pops (2, 3), then runs straight up through (1, 3) to (0, 3) on the top edge. There, left is the last open neighbour pushed, so it runs left along the top row to (0, 0), then down the left column through (1, 0), (2, 0) and (3, 0) to the target at (4, 0). The route is 10 steps long. BFS on the same board finds a route of 5 steps. Both prove the target can be reached; only the BFS route is the shortest.
Written recursively, grid DFS is a few lines: mark the cell, then call the function on each open neighbour. On a big open grid the chain of calls can reach every cell, and a 1000 by 1000 grid could need a million nested calls, far past the call stack limit of most languages. The explicit stack on this page has no such limit.
Time: each cell is pushed at most once and looks at four neighbours, so the work grows with R × C. Space: the visited marks cover every cell, and on an open grid the stack can hold a large share of them before the search backs up.