TExcelTAD
Home › Game AI › Graphs & Grids

Graphs & Grids

Every pathfinding algorithm in this section works on a graph: a set of nodes (places an agent can be) joined by edges (moves it can make), each edge with a cost (distance, time, danger). The algorithm never sees your level. It only asks one question over and over: "what are the neighbours of this node, and what does it cost to get there?" Choosing how to turn a level into a graph is the first, and often the biggest, pathfinding decision.

Three ways to build the graph

Representation Nodes Good for Weak at
Grid one per tile or cell tile-based games, RTS, roguelikes, quick prototypes big open worlds (millions of cells), smooth paths
Waypoint graph hand-placed or generated points corridors, simple levels, older shooters open areas (agents zig-zag between points), every edit needs re-linking
Navigation mesh convex polygons of walkable floor 3D levels, all major engines needs a build step; dynamic changes cost a rebuild

This section starts with grids because they're easy to print and reason about, then moves on to Navigation Meshes. The search algorithms are the same for all three; only the neighbour function changes.

Note: If graphs are new to you, the DSA course covers them from scratch: Graphs, Graph Traversal and Dijkstra's Algorithm.

A grid is an implicit graph

You don't store a grid's edges. A cell (x, y) is a node, and its neighbours are computed on demand from the map: the four cells beside it (4-connected) or those plus the four diagonals (8-connected). Walls simply aren't neighbours. For speed, engines often number cells with a single integer, id = y * width + x, so a node fits in an int and per-node data lives in flat arrays instead of dictionaries.

Diagonal moves need two rules:

  • Cost: a diagonal step is longer, so it costs √2 ≈ 1.414 (or the integer pair 10/14 to avoid floats).
  • Corner cutting: moving diagonally between two walls that touch at a corner would squeeze the agent through a gap of zero width. Most games allow a diagonal only when both orthogonal cells beside it are free.
csharp · try it yourself
using System;
using System.Collections.Generic;

string[] map =
{
    "#######",
    "#.....#",
    "#.#...#",
    "#..#..#",
    "#.....#",
    "#######",
};
int w = map[0].Length, h = map.Length;
bool Free(int x, int y) => x >= 0 && y >= 0 && x < w && y < h && map[y][x] != '#';

var straight = new (int dx, int dy)[] { (0, -1), (1, 0), (0, 1), (-1, 0) };
var diagonal = new (int dx, int dy)[] { (1, -1), (1, 1), (-1, 1), (-1, -1) };

List<(int x, int y, double cost)> Neighbours(int x, int y, bool eight)
{
    var result = new List<(int, int, double)>();
    foreach (var (dx, dy) in straight)
        if (Free(x + dx, y + dy)) result.Add((x + dx, y + dy, 1.0));
    if (eight)
        foreach (var (dx, dy) in diagonal)
            // no corner cutting: both side cells must be free
            if (Free(x + dx, y + dy) && Free(x + dx, y) && Free(x, y + dy))
                result.Add((x + dx, y + dy, Math.Sqrt(2)));
    return result;
}

foreach (var (x, y) in new[] { (2, 3), (4, 2) })
{
    Console.WriteLine(
quot;cell ({x},{y}) = id {y * w + x}"); Console.WriteLine(" 4-connected: " + string.Join(" ", Neighbours(x, y, false).ConvertAll(n =>
quot;({n.x},{n.y})"))); Console.WriteLine(" 8-connected: " + string.Join(" ", Neighbours(x, y, true).ConvertAll(n =>
quot;({n.x},{n.y}):{n.cost:F2}"))); } int nodes = 0, edges4 = 0, edges8 = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) if (Free(x, y)) { nodes++; edges4 += Neighbours(x, y, false).Count; edges8 += Neighbours(x, y, true).Count; } Console.WriteLine(
quot;{nodes} walkable cells, {edges4 / 2} edges (4-connected), {edges8 / 2} edges (8-connected)");
cell (2,3) = id 23
  4-connected: (2,4) (1,3)
  8-connected: (2,4):1.00 (1,3):1.00 (1,4):1.41
cell (4,2) = id 18
  4-connected: (4,1) (5,2) (4,3) (3,2)
  8-connected: (4,1):1.00 (5,2):1.00 (4,3):1.00 (3,2):1.00 (5,1):1.41 (5,3):1.41 (3,1):1.41
18 walkable cells, 23 edges (4-connected), 33 edges (8-connected)

Notice cell (2,3): it has walls above and to the right, so it has two straight exits, and of its four diagonals only (1,4) survives. (3,4) is free floor, but stepping there would clip the wall at (3,3), so the corner rule removes it. Cell (4,2) keeps three diagonals; the fourth, (3,3), is a wall. Each edge is counted twice in the loop (once from each end), hence the / 2.

Costs are design data

An edge cost doesn't have to be distance. Make it whatever the agent should avoid: mud and stairs cost more, a lit corridor costs more for a thief, cells near a turret cost more for a soldier. The same search then produces different, believable routes for different characters, and a level designer can tune behaviour by painting costs instead of writing code. Dijkstra's Algorithm uses exactly this.

Cost idea Effect
Terrain multipliers (road 1, grass 2, swamp 5) units prefer roads, like real armies
Danger from an influence map soldiers route around enemy fire
A small penalty per turn straighter, more natural paths
"Occupied by a friend" penalty fewer traffic jams in corridors

Keep every cost at least the straight-line distance of the move. Cheaper-than-distance edges break the guarantees of A* and its heuristics.

How big is too big?

A 256 × 256 grid has 65,536 nodes; a search may touch tens of thousands of them, which is fine once, but not for 200 units every frame. The usual answers, all covered later: search fewer nodes with A*, share one search between many units with Flow Fields, use bigger nodes with Navigation Meshes, and spread searches over several frames (see Field Notes: Performance).

Test yourself

Why is a diagonal move between two wall cells that touch at a corner usually forbidden?

  1. It costs too much
  2. The agent would squeeze through a zero-width gap and clip the walls
  3. A* can't handle diagonals
  4. It makes the grid 4-connected

What does a pathfinding algorithm actually need from your level?

  1. The whole mesh
  2. A neighbour function that returns adjacent nodes and the cost to reach them
  3. Textures
  4. The physics engine

Which cost for a 1-cell diagonal step matches its real length?

  1. 1
  2. 2
  3. about 1.414
  4. 0.5