Watch Breadth-First Search (BFS) find paths through complex grids. Interactive matrix explorations.
About this algorithm
Grid BFS finds the shortest route between two cells of a grid when you can step up, down, left or right and walls block the way. Each cell is a node and each step to a side neighbour is an edge, so the search spreads from the start in rings: every cell 1 step away, then every cell 2 steps away, until a ring touches the target.
Use grid BFS for the fewest moves through a maze, a game map or a floor plan, and for anything that spreads one cell per turn, such as fire, flood or rot moving through a grid. Pick grid DFS instead when you only need to know whether the target can be reached, or when you are labelling connected areas like islands, because then the order of visits does not matter. If entering some cells costs more than others, BFS no longer finds the cheapest route; use Dijkstra on the grid.
Put the start cell in a queue and mark it visited. This page checks neighbours in the order right, down, left, up.
Take every cell in the current ring. For each one, look at its four side neighbours. Skip a neighbour that is off the grid, a wall or already visited. Otherwise mark it visited, remember which cell you came from, and add it to the next ring. On this page one step of the animation lights a whole ring, so counting steps counts the distance.
The moment the target joins a ring, stop. Its ring number is the length of the shortest route. If a ring comes up empty before that, the walls have cut the target off.
Follow the remembered parent cells from the target back to the start. That chain is a shortest route; there may be others of the same length.
The page sizes the grid to your screen, picks a random start and target, and scatters walls over about 15% of the cells, so your board will differ. Take a board of 5 rows and 7 columns with no walls, the start at row 2, column 3 (counting from 0) and the target at row 4, column 0. Ring 1 has 4 cells, ring 2 has 8, ring 3 has 10 and ring 4 has 8. Ring 5 reaches the target, so the shortest route is 5 steps. On an open grid that is simply the row gap plus the column gap, 2 + 3. The route found goes down from (2, 3) to (4, 3), then left along the bottom row to (4, 0). Draw a wall across that route and run again to watch the rings bend around it.
Put several start cells in the first ring and the same loop measures every cell's distance to its nearest start. That is how the Rotting Oranges page spreads rot from every rotten orange in the same minute.
Time: each cell joins a ring at most once and checks at most four neighbours, so the work grows with the number of cells, R × C. Space: the visited marks and parent links take one entry per cell, and a single ring can hold a large share of the cells at once.