TExcelTAD
Home › Game AI › Breadth-First Search

Breadth-First Search

Breadth-first search (BFS) is the simplest pathfinder that is actually correct. It explores outward from the start in rings: first every node one step away, then every node two steps away, and so on. Because it reaches nodes in order of step count, the first time it reaches the goal it has found a path with the fewest steps. When every move costs the same, as on a plain 4-connected grid, that is also the shortest path.

The algorithm

BFS needs two things: a queue (first in, first out) of nodes to explore, called the frontier, and a came-from map that records, for each discovered node, the node we reached it from.

  1. Put the start in the frontier and mark it discovered.
  2. Take the oldest node out of the frontier. If it's the goal, stop.
  3. For each neighbour that hasn't been discovered: record where it came from and add it to the frontier.
  4. Repeat from step 2 until the frontier is empty (no path).

To get the path, walk the came-from map backwards from the goal to the start and reverse it.

Step through it on a small grid-shaped graph. Each node is a floor cell (columns a–d, rows 1–3); cell b2 is a wall, so it isn't in the graph. Neighbours are taken in alphabetical order:

The same search in C#, printing the visit order the animation shows, then the path to the far corner d3:

csharp · try it yourself
using System;
using System.Collections.Generic;

string[] edges = { "a1-b1", "b1-c1", "c1-d1", "a1-a2", "c1-c2", "d1-d2", "c2-d2", "a2-a3", "c2-c3", "d2-d3", "a3-b3", "b3-c3", "c3-d3" };
var adj = new SortedDictionary<string, List<string>>(StringComparer.Ordinal);
foreach (string e in edges)
{
    string[] p = e.Split('-');
    if (!adj.ContainsKey(p[0])) adj[p[0]] = new List<string>();
    if (!adj.ContainsKey(p[1])) adj[p[1]] = new List<string>();
    adj[p[0]].Add(p[1]);
    adj[p[1]].Add(p[0]);
}
foreach (var list in adj.Values) list.Sort(StringComparer.Ordinal);   // alphabetical, like the animation

var cameFrom = new Dictionary<string, string> { ["a1"] = "" };
var steps = new Dictionary<string, int> { ["a1"] = 0 };
var frontier = new Queue<string>();
frontier.Enqueue("a1");
var order = new List<string>();
while (frontier.Count > 0)
{
    string cur = frontier.Dequeue();
    order.Add(cur);
    foreach (string next in adj[cur])
    {
        if (cameFrom.ContainsKey(next)) continue;
        cameFrom[next] = cur;
        steps[next] = steps[cur] + 1;
        frontier.Enqueue(next);
    }
}
Console.WriteLine("visit order: " + string.Join(" -> ", order));

var path = new List<string>();
for (string n = "d3"; n != ""; n = cameFrom[n]) path.Add(n);
path.Reverse();
Console.WriteLine(
quot;path to d3: {string.Join(" -> ", path)} ({steps["d3"]} steps)");
visit order: a1 -> a2 -> b1 -> a3 -> c1 -> b3 -> c2 -> d1 -> c3 -> d2 -> d3
path to d3: a1 -> a2 -> a3 -> b3 -> c3 -> d3 (5 steps)

There are several 5-step paths to d3; BFS returns whichever its neighbour order discovers first. That is worth knowing: if your units all take the same "staircase" route, the neighbour order is the reason, and Path Smoothing or tie-breaking (see Heuristics) is the fix.

BFS on a game map

Now on a real grid map. S is the guard, G the goal, # walls. The search stops as soon as it takes the goal out of the queue (early exit), counts how many cells it expanded (took out of the frontier), and draws the path with *:

csharp · try it yourself
using System;
using System.Collections.Generic;

string[] map =
{
    "##############",
    "#S...####...G#",
    "#.##########.#",
    "#.#........#.#",
    "#.#.######.#.#",
    "#...######...#",
    "##############",
};
(int x, int y) Find(char c)
{
    for (int y = 0; y < map.Length; y++)
        if (map[y].IndexOf(c) >= 0) return (map[y].IndexOf(c), y);
    throw new Exception(
quot;no {c}"); } var start = Find('S'); var goal = Find('G'); var dirs = new (int dx, int dy)[] { (0, -1), (1, 0), (0, 1), (-1, 0) }; // up, right, down, left var cameFrom = new Dictionary<(int x, int y), (int x, int y)> { [start] = start }; var frontier = new Queue<(int x, int y)>(); frontier.Enqueue(start); int expanded = 0; while (frontier.Count > 0) { var cur = frontier.Dequeue(); expanded++; if (cur == goal) break; // early exit foreach (var (dx, dy) in dirs) { var next = (x: cur.x + dx, y: cur.y + dy); if (map[next.y][next.x] == '#' || cameFrom.ContainsKey(next)) continue; cameFrom[next] = cur; frontier.Enqueue(next); } } var grid = Array.ConvertAll(map, row => row.ToCharArray()); int length = 0; for (var c = cameFrom[goal]; c != start; c = cameFrom[c]) { grid[c.y][c.x] = '*'; length++; } foreach (var row in grid) Console.WriteLine(new string(row)); Console.WriteLine(
quot;path: {length + 1} steps, expanded {expanded} of {cameFrom.Count} discovered cells");
##############
#S...####...G#
#*##########*#
#*#********#*#
#*#*######*#*#
#***######***#
##############
path: 23 steps, expanded 27 of 27 discovered cells

The pocket to the right of S looks like the way to the goal, but it's a dead end; BFS doesn't care, it simply finds the shortest route that exists. Notice the cost of that certainty: BFS expanded all 27 floor cells, the dead-end pocket included, before it took the goal out of the queue. On this winding map almost every cell is on the way anyway, but on an open map BFS still floods in every direction, because it has no idea where the goal is. A* Search fixes exactly that.

When BFS is the right tool

Use BFS when Don't use it when
every move costs the same (4-connected tiles, turn-based steps) moves have different costs (diagonals, mud, roads): use Dijkstra
you want distances to every cell from one source: a "Dijkstra map" for a roguelike, or the field in Flow Fields you need one path across a huge map: use A*
you need "all tiles within N moves" for a tactics game's movement range

Tip: For a tactics game's movement range, run BFS from the unit without a goal and stop expanding any node whose step count equals the unit's move points. The discovered set is the blue "you can move here" overlay.

Test yourself

Why does BFS find the path with the fewest steps?

  1. It sorts nodes by distance to the goal
  2. It expands nodes in order of how many steps they are from the start
  3. It tries every possible path
  4. It uses a stack

What is the came-from map used for?

  1. Storing walls
  2. Rebuilding the path by walking back from the goal, and marking nodes as discovered
  3. Sorting the queue
  4. Counting edges

On which map is BFS NOT guaranteed to find the cheapest path?

  1. A 4-connected grid where every step costs 1
  2. A grid where mud tiles cost 5 and floor tiles cost 1
  3. A waypoint graph with equal edge costs
  4. A maze with one solution