Maze Pathfinding in TypeScript: BFS Solving and DFS Generation

11 min read
AlgorithmVisualizationTypeScriptGraph

Open the Maze Runner demo and move the blue dot from the upper-left corner to the star at the lower right. Press Show Solution to reveal the route found by breadth-first search (BFS). Try a few moves yourself, then compare your route with the yellow markers.

The demo builds its maze with a depth-first search (DFS) style procedure and uses BFS to find the solution. This article follows the current TypeScript implementation to explain the two roles and what a shortest path means here.

Controls and the solution display

  1. On a computer, use the arrow keys or W, A, S, and D to move one cell. A wall blocks movement. The timer starts with your first successful move.
  2. On a phone, use the direction buttons below the maze or swipe. The dominant horizontal or vertical displacement must exceed 20px to request one step. A longer swipe does not move through several cells at once.
  3. Press Show Solution. Yellow markers appear along the route from the upper-left start to the lower-right goal. During an active game, you can still move, and the timer keeps running. This does not calculate only the remaining route from your current position.
  4. Press New Maze to generate a maze and reset the position, visited cells, solution display, timer, and result overlay. It also cancels a pending win callback so that the previous game's result cannot appear over the next maze.

The blue dot is your position, pale purple marks cells you have visited, and yellow marks the solution. The goal star stays in the lower-right corner. The display does not animate every cell BFS examined, so yellow markers do not reveal the full search area.

A 15-by-15 grid with walls between cells

The maze is a two-dimensional array of 15 rows and 15 columns: 225 cells. Each cell stores its row, column, and four boolean walls named top, right, bottom, and left. A false wall allows passage in that direction. The cells themselves are not classified as either wall cells or passage cells.

Connecting adjacent cells removes the wall on both sides. For a downward passage, the upper cell's bottom and the lower cell's top both become false. The outer boundary stays closed to prevent leaving the grid. SVG lines and shapes render the maze.

Building the maze with a DFS-style procedure

generateMaze starts with every wall closed. It marks the upper-left cell as visited and puts it on a stack. The last cell on that stack is the working position. If an unvisited neighbor exists, the procedure chooses one at random, removes the connecting walls, and pushes that neighbor onto the stack.

When no unvisited neighbor remains, stack.pop() returns to the previous cell. The procedure keeps advancing and backtracking until the stack is empty. It then resets all generation-time visited flags to false. A separate set tracks the player's visited cells.

Each new passage connects one previously unvisited cell. Connecting 225 cells therefore creates 224 passages and a connected tree with no cycles. While those generation conditions hold, exactly one simple path connects any two cells. Princeton's Undirected Graphs material describes a perfect-maze generator using the same wall representation.

Finding the shortest path with BFS

Show Solution calls solveMaze, which puts the upper-left coordinate, [0, 0], into a queue. It removes the first entry with queue.shift() and checks the four neighboring cells. A candidate must be inside the grid, unvisited, and reachable through an open wall.

On discovering a candidate, the solver marks it visited, records the previous cell in parent, and appends it with queue.push(). This first-in, first-out order examines cells in increasing distance from the start: one step away, then two steps, then three.

After reaching the goal, the solver follows the recorded parents backwards. This excerpt from the current implementation inserts coordinates at the front of the result, starting at the lower-right corner and ending at the start cell.

const path: [number, number][] = []
let cur: [number, number] | null = [ROWS - 1, COLS - 1]
while (cur) {
  path.unshift(cur)
  cur = parent.get(`${cur[0]},${cur[1]}`) ?? null
}

Shortest means the fewest steps when every move between cells costs one. Princeton's BFS explanation likewise defines a shortest route by its number of edges. Terrain with unequal movement costs and diagonal moves are outside this demo.

Why generate with DFS and solve with BFS?

The DFS-style generator decides where passages will exist. The BFS solver finds a route through those completed passages. They have different inputs and goals, so it helps to read them as separate procedures.

In this maze, which has no cycles, there is only one simple route to the goal. Correct DFS and BFS path finders would therefore reach the same route. In an unweighted graph containing cycles and alternative routes, however, DFS does not guarantee the shortest path. Simply replacing the BFS queue with a stack does not preserve that guarantee.

Does the speed of the yellow markers measure BFS?

The solveMaze call calculates the route first. A 40ms timer then increases the number of visible markers by one cell. It reveals a route that has already been calculated; it does not run each BFS search step at a 40ms interval. Browser scheduling can also change the display interval, so the animation cannot establish computation time or frame rate.

The current solver is fixed to BFS. There are no buttons to switch to A* or DFS. This explanation assumes the connected mazes produced by the generator; the demo is not an editor or validator for arbitrary walls or unreachable inputs.

How Pac-Man and Snake differ

In the Pac-Man demo, ghosts choose among local movement candidates using distance to the player and random choices. That is different from solving the whole maze with BFS. In the Snake demo, a person chooses the direction with arrow keys or swipes. Treat these controls separately from Maze Runner's shortest-path calculation.

Return to the maze and compare your visited cells with the yellow solution. Following blocked walls, backtracking from dead ends, and tracing the start-to-goal route connects the wall data to the search procedure.

Go deeper on this topic

Browser Game Development

Game loop design, collision detection, pathfinding, and tooling for browser games

Article 4 of 7 in this series.

View topic page

Use the topic hub as a map, then continue to the next article in the series. New here? Start at the home hub →