← MAIN
LAB // PATHFINDING

PATHFIND

Draw walls, paint swamp, then race seven searches on the same map.
MAP 41×41 RACERS 7 STATUS READY

HOW TO USE

The goal is to find the cheapest route from S to G. Each search explores the map in its own order, and the leaderboard ranks them by the cost of the path they found and by how many cells they expanded.

Choose a tool and drag on the map to paint walls or terrain, or move S and G. Pick a PRESET or press GENERATE under MAP for a new maze.

Press RACE to start all ticked searches on the same map. Watch the panels, or switch to FOCUS and pick one search to see it large.

Drag on the map to paint. Hover any cell for its terrain and its distance to the goal.
RACE
LEADERBOARD
Race to see the ranking. Optimal means the cost equals the Dijkstra reference on this map.
#ALGORITHMEXPANDEDPEAK FRONTIERPATH COSTOPTIMAL
MAP
PRESET
SWAMP 0%
SEARCH
ALGORITHMS IN THE RACE
PLAYBACK
SPEED
More settings
GENERATOR
SIZE
SEED (same seed, same map)
PRESET NOTE
HEURISTIC (greedy, A*, weighted A*)
WEIGHT w 2.0
HOVER A CELL
Start a race to see how each search scores the cells it reaches.

HOW IT WORKS

Every search keeps a frontier, the set of cells it has found but not yet expanded, and expands one cell at a time: it takes a cell from the frontier and looks at its neighbours. The seven racers differ only in how they choose the next cell. All of them run on the same map, with the same neighbour order and the same tie-breaking, so their counts can be compared directly.

Map, moves and costs

The map is a grid of cells. A wall cannot be entered. Open ground has terrain value 1, mud has 3 and swamp has 5. Each move goes to one of the neighbours, in a fixed order: up, right, down, left123. With diagonal moves on, the four diagonal neighbours are added after them, but only when both orthogonal cells beside the diagonal are open, so a diagonal never squeezes past a wall corner4.

Entering a cell costs its terrain value, and a diagonal step is longer than an orthogonal one. The cost of a step a \to b is therefore the length of the step times the terrain of the cell entered56. The cost of a path is the sum of its steps7.

89
c(a \to b) = \ell_{ab}\; t_b, \qquad \ell_{ab} = \begin{cases} 1 & \text{orthogonal} \\ \sqrt{2} & \text{diagonal} \end{cases}, \qquad C(P) = \sum_{k=1}^{m} c(p_{k-1} \to p_k)

Here t_b is the terrain value of the cell b that is entered, and P = (p_0, \dots, p_m) is a path from start to goal. The constant \sqrt{2} is the diagonal length. The search counts a cell's cost once per entry, so a long walk through swamp is expensive even when it is short in steps.

Ties. The frontier is a heap ordered by priority, then by push number, so equal priorities come out in the order they were added1011. Together with the fixed neighbour order, this makes every race repeatable for a given map.

Breadth-first and depth-first

Breadth-first search (BFS) explores in rings: first every cell one step from the start, then every cell two steps away, and so on. It keeps a first-in, first-out queue, and it marks a cell as seen when it is first discovered. The first time the goal is reached gives the fewest steps. BFS is optimal when every step costs the same. On a map with swamp it still returns the fewest steps, which can be the expensive route1213.

1213
function BFS(grid, start, goal):
    queue ← [start];  start is seen
    while queue is not empty:
        u ← remove the front of queue
        expand u
        if u = goal: return the path from start to goal
        for each neighbour v of u:
            if v is not seen:
                v is seen;  parent(v) ← u
                add v to the back of queue
    return no path

Ideas in the full version. BFS does not need a cost to find the route, so its g is recorded only so the path cost can be reported. A cell is seen when it is discovered, not when it is expanded, so each cell enters the queue at most once. The step records feed the animation and the counters: \text{EXPANDED} is the number of steps and \text{GENERATED} is the number of discoveries.

Depth-first search (DFS) follows one branch as far as it goes, then backs up to the last fork. It uses a last-in, first-out stack. The first route it reaches the goal by is the one it returns. That route is rarely the shortest, so DFS is not optimal in general1415.

1415
function DFS(grid, start, goal):
    stack ← [start]
    while stack is not empty:
        u ← pop the top of stack
        if u is closed: continue
        close u;  parent(u) ← the cell it was pushed from
        expand u
        if u = goal: return the path from start to goal
        push each open neighbour of u onto stack

Ideas in the full version. A cell can be pushed several times, once from each neighbour that reaches it. The \text{closed} check at pop discards the copies. The parent is set when a cell is expanded, so the path follows the branch that actually reached the goal. The stack can hold up to one entry per edge, which is the memory cost in the table below.

Best-first: Dijkstra, greedy, A* and weighted A*

Four of the racers share one loop. Each cell is given a priority, and the frontier pops the lowest first. The cost so far is g, and the heuristic h is an estimate of the remaining cost to the goal. The priority decides the algorithm:

1617
f_{\text{UCS}} = g, \qquad f_{\text{greedy}} = h, \qquad f_{\text{A*}} = g + h, \qquad f_{w\text{A*}} = g + w\,h

Uniform cost (Dijkstra's algorithm) orders by g alone, so it expands the cell that is cheapest to reach from the start. It is optimal for any positive costs, and the lab uses it as the reference: its cost is the optimum every other path is compared with. Greedy best-first orders by h alone, so it heads for the goal as if the map were empty. It is fast, but it ignores the cost already paid and the terrain, so it can walk through swamp. A* orders by g + h, the cost paid plus the estimate of what remains18.

Every best-first search keeps the best g found so far for each cell. A neighbour is queued only when the route through the current cell is cheaper than any route found before, and then its parent is updated1920.

2111
function BEST-FIRST(grid, start, goal, priority):
    g(start) ← 0;  push start with priority(start)
    while the frontier is not empty:
        u ← pop the cell with the lowest priority
        if u is closed: continue
        close u;  expand u
        if u = goal: return the path from start to goal
        for each open neighbour v of u:
            if g(u) + c(u → v) < g(v):
                g(v) ← g(u) + c(u → v);  parent(v) ← u
                push v with priority(v)

Ideas in the full version. The push number is the second key of the heap, so a cell pushed earlier pops earlier when priorities tie. A cell can be pushed more than once when a cheaper route is found; the older entry is skipped at pop time because its cell is already closed. The heuristic is only read by greedy, A* and weighted A*. Dijkstra's priority ignores it, so its h is not used at all.

Heuristics: admissible and consistent

Admissible means h never overestimates the true remaining cost, and that is what makes A* return an optimal path. Consistent (monotone) means h(a) \le c(a \to b) + h(b) for every step, so a cell is never reopened once expanded. Every terrain value is at least 1, so each estimate below uses cost 1 per cell, and a diagonal step costs \sqrt{2}2223.

22
h_{\text{Manhattan}} = |dx| + |dy|, \qquad h_{\text{Euclid}} = \sqrt{dx^2 + dy^2}, \qquad h_{\text{octile}} = \max(|dx|, |dy|) + (\sqrt{2} - 1)\min(|dx|, |dy|)

Here dx and dy are the distances from the cell to the goal along each axis. Octile is exact on empty ground with eight-way moves, because it counts the diagonal steps and then the straight ones.

Heuristic4-way moves8-way moves
Manhattanadmissible, consistentnot admissible: a diagonal step costs √2, but Manhattan counts it as 2, so A* can return a longer path
Euclideanadmissible, consistent (weaker than Manhattan)admissible, consistent (weaker)
Octileadmissible, consistentexact on empty ground, admissible and consistent

The lab uses octile by default. With diagonal moves off, Manhattan is the tightest admissible choice, and with diagonals on, octile is. Manhattan with diagonals still runs, and the leaderboard marks a path it makes suboptimal24.

Weighted A*

Weighted A* uses f = g + w\,h with w \ge 1. A larger w pulls the search toward the goal, so fewer cells are expanded, but the path may be longer. With an admissible heuristic, the path cost is at most w times the optimum. The default is w = 2, so a route is never more than twice the best one, and w = 1 is plain A*2526.

Bidirectional BFS

Bidirectional BFS runs two breadth-first searches, one from the start and one from the goal, and stops when they meet. Each side grows one whole level at a time, and the side with the smaller next level goes first. Each side only has to cover about half the route, so the two searches together can reach the meeting point with fewer expansions than one search needs for the whole route. The race shows this on a given map27.

The first meeting is not always the shortest, so each meeting is scored by its total steps, \text{depth}_{\text{start}}(v) + \text{depth}_{\text{goal}}(v), and the search keeps going until the best total is no more than the two completed levels reach. Like BFS, it counts steps rather than terrain cost, so it can be optimal in steps and still pay more on swamp2829.

2829
function BIDIRECTIONAL-BFS(grid, start, goal):
    grow a BFS from start (forward) and from goal (backward)
    always expand the side with the smaller next level, one whole level at a time
    when a cell is seen by both sides, record the total steps through it
    stop when the best total is no more than the levels both sides have finished
    return the path through the best meeting cell

Ideas in the full version. The two sides take turns by level, not by cell, so when a level is finished both sides have exactly the same completed depth. The cost of a step is charged to the cell that is entered, which depends on the direction the step is walked, so the backward side charges the cell it came from. The stop test is what keeps the path short: a shorter path would have a cell that both sides already found.

Mazes and maps

The generators build a map of walls and open cells from a seed. The lattice generators (recursive backtracker and Prim's) work on the odd coordinates, where each cell is an open junction. A passage between two junctions is carved by opening the wall cell halfway between them, so every junction is joined to the start by exactly one route. The start is the junction at (1, 1), and the goal is the last junction in the bottom-right corner3031.

3233
\text{carve}(x, y \to x', y') : \quad \text{open}\bigl(\tfrac{x + x'}{2},\ \tfrac{y + y'}{2}\bigr) \ \text{and}\ \text{open}(x', y'), \qquad (x', y') = (x, y) + (\pm 2, 0) \ \text{or}\ (0, \pm 2)

Here (x, y) is a junction and (x', y') is a junction two cells away. The recursive backtracker carves into a random unvisited junction and backs up when none is left, which gives long winding corridors. Prim's algorithm grows the same kind of tree from a random frontier wall, which gives many short branches. Both are perfect mazes: exactly one route joins any two cells34.

The scatter generator opens each interior cell with probability 72% (walls at 28%), so a route exists only by luck, and the lab reports when none does. Rooms places rectangles and joins them with L-shaped corridors. Open ground has no walls, so only the terrain costs and the walls you draw matter. Swamp from the slider turns each open cell into swamp with the chosen percent chance, and the start and goal stay open353637.

Complexity and what to watch

AlgorithmTime (cells)MemoryOptimal on this map?
BFSO(V + E)O(V) frontierfewest steps; cost only on plain ground
DFSO(V + E)O(V) closed set; this version's stack holds up to O(E) entriesno
DijkstraO(E log V)O(V)yes
GreedyO(E log V) worst caseO(V)no
A*O(E log V) with a good hO(V)yes, with an admissible h
Weighted A* (w)fewer expansions as w growsO(V)within w times the optimum
Bidirectional BFSabout 2·b^(d/2) instead of b^dO(V)fewest steps only

V is the number of cells, E the number of moves, b the branching factor (4, or 8 with diagonals) and d the length of the route in steps. The lab counts expansions and generated cells, which is what these bounds count. The race compares the searches on one map; it does not measure the bounds directly.

Checks in the test suite

Uniform cost and A* match a brute-force reference on random maps, with and without diagonals38. BFS is optimal on unit-cost grids39. Weighted A* stays within its bound26. Bidirectional BFS is step-optimal like BFS, and it finishes the level it is on before stopping40. Every search agrees on which cells are reachable41. The browser core and the Python package agree on fixed seeds42.