Math for Programming / Part 2: Math inside the computer

Pathfinding: the shortest way around

How does a game enemy find its way around walls? By treating the map as a graph and letting a search spread out from the start like a ripple.

Lesson 13 of 13About 12 minutesBuilds on: absolute value and distance

A grid is a graph

In computer science, a graph is not a chart. It is a set of points, called nodes, connected by links, called edges. A road map is a graph: towns are nodes and roads are edges. So is a social network, and so is a tile-based game level. Each open tile is a node, and it has an edge to each open neighbor above, below, left, and right.

Measuring distance on a grid

If a character can only move in four directions, the number of steps from (0, 0) to (3, 2) with no walls in the way is 3 + 2 = 5. This is the Manhattan distance, |x₂ − x₁| + |y₂ − y₁|, named for walking city blocks. If diagonal moves are allowed and cost one step each, the distance becomes the larger of the two differences, max(3, 2) = 3. The straight-line Pythagorean distance, √(3² + 2²) ≈ 3.61, is what a bird would fly. Three answers, three different rules of movement.

Breadth-first search: spreading like a ripple

Walls make distance harder to predict. Breadth-first search (BFS) handles them with a simple idea. Start at the beginning and mark it 0. Mark every open neighbor 1. Mark their unmarked neighbors 2, and so on, like a ripple spreading across a pond. The first time the ripple reaches the goal, its number is the length of the shortest path. To find the path itself, walk backward from the goal, always stepping to a neighbor whose number is one smaller.

Figure

Click squares to add or remove walls. The numbers show BFS distances from the blue start.

GDScript
func bfs(start: Vector2i, goal: Vector2i, walls: Dictionary) -> int:
    var dist := {start: 0}
    var queue := [start]
    while not queue.is_empty():
        var cell: Vector2i = queue.pop_front()
        if cell == goal:
            return dist[cell]
        for step in [Vector2i.RIGHT, Vector2i.LEFT, Vector2i.UP, Vector2i.DOWN]:
            var next: Vector2i = cell + step
            if not walls.has(next) and not dist.has(next) and in_bounds(next):
                dist[next] = dist[cell] + 1
                queue.push_back(next)
    return -1   # the goal cannot be reached
# in_bounds() is a small helper that checks the grid edges.

The queue is the key: cells are handled first-in, first-out, so all distance-1 cells are finished before any distance-2 cell. That order is what guarantees the shortest path.

Smarter searches

BFS explores in every direction equally, even away from the goal. The famous A* (“A star”) algorithm adds a guess, usually the Manhattan or straight-line distance to the goal, so it explores promising cells first. Dijkstra’s algorithm handles edges with different costs, such as mud that takes three times as long to cross. Godot includes ready-made tools for this, such as AStarGrid2D, but they all build on the ripple idea above.

Common mistake

Using the straight-line distance as the path length. An enemy 3 tiles away through a wall might be 15 steps away by path. The distance formula measures “as the crow flies”; pathfinding measures “as the character walks.”

Where this comes from in school math

Absolute value and the distance formula come from Algebra I and geometry. Counting paths on a grid is a classic combinatorics problem, and graph theory is a branch of discrete mathematics, the math most used in computer science.

Where you will see it

  • Games: enemies chasing players and units moving around obstacles.
  • Maps: driving directions are shortest paths on a road graph.
  • Networks: internet data is routed through a graph of connections.
  • Puzzles: mazes and sliding puzzles are searches through a graph of positions.

Exercises

What is the Manhattan distance from (2, 7) to (6, 4)?

|6 − 2| + |4 − 7| = 4 + 3 = 7.

In a BFS, a cell is marked 5. What can you say about each of its open neighbors?

Each is marked 4, 5, or 6. Neighbors differ by at most one step.

Why does BFS use a queue instead of picking any cell to explore next?

First-in, first-out order finishes every cell at one distance before moving on, which guarantees the first arrival at the goal is along a shortest path.