Dijkstra's Algorithm
BFS minimizes the number of steps. Games rarely want that. A road is quicker than a swamp, a diagonal is longer than a straight step, and a thief should prefer shadows. Dijkstra's algorithm finds the path with the lowest total cost when every edge cost is zero or positive. It's BFS with one change: instead of a first-in-first-out queue, the frontier is a priority queue ordered by the cost so far, g(n), so the cheapest unfinished node is always expanded next.
The algorithm
- Set
g(start) = 0and every other node's cost to ∞. Put the start in the priority queue. - Take the node with the lowest
gout of the queue. Its cost is now final ("settled"). If it's the goal, stop. - For each neighbour:
newCost = g(current) + edgeCost. If that beats the neighbour's best cost so far, relax the edge: store the new cost, remembercurrentas its came-from, and (re)insert it into the queue. - Repeat from step 2.
Here it is on a waypoint graph of an outdoor level. The direct trail from Camp to Bridge costs 4, but going through the Ford costs 2 + 1 = 3, so Bridge gets relaxed from 4 down to 3:
The same search in C#. It picks the closest unsettled node with a simple loop (ties broken alphabetically, like the animation) and prints every settle and every relaxation:
using System;
using System.Collections.Generic;
using System.Linq;
string[] edges = { "Camp-Bridge:4", "Camp-Ford:2", "Ford-Bridge:1", "Bridge-Mill:5", "Ford-Swamp:3", "Swamp-Keep:9",
"Mill-Keep:3", "Hill-Mill:2", "Ford-Hill:7", "Hill-Tower:4", "Tower-Keep:2" };
var adj = new Dictionary<string, List<(string to, int cost)>>();
foreach (string e in edges)
{
string[] p = e.Split('-', ':');
int c = int.Parse(p[2]);
foreach (var (a, b) in new[] { (p[0], p[1]), (p[1], p[0]) })
{
if (!adj.ContainsKey(a)) adj[a] = new();
adj[a].Add((b, c));
}
}
foreach (var list in adj.Values) list.Sort((x, y) => string.CompareOrdinal(x.to, y.to));
var dist = adj.Keys.ToDictionary(k => k, k => int.MaxValue);
var prev = new Dictionary<string, string>();
var settled = new HashSet<string>();
dist["Camp"] = 0;
while (true)
{
string? u = dist.Where(kv => !settled.Contains(kv.Key) && kv.Value != int.MaxValue)
.OrderBy(kv => kv.Value).ThenBy(kv => kv.Key, StringComparer.Ordinal)
.Select(kv => kv.Key).FirstOrDefault();
if (u == null) break;
settled.Add(u);
Console.WriteLine(quot;settle {u} at {dist[u]}");
foreach (var (to, cost) in adj[u])
{
if (settled.Contains(to) || dist[u] + cost >= dist[to]) continue;
string old = dist[to] == int.MaxValue ? "inf" : dist[to].ToString();
dist[to] = dist[u] + cost;
prev[to] = u;
Console.WriteLine(quot; relax {u}->{to}: {old} -> {dist[to]}");
}
}
var path = new List<string> { "Keep" };
while (prev.ContainsKey(path[^1])) path.Add(prev[path[^1]]);
path.Reverse();
Console.WriteLine(quot;Camp to Keep: {string.Join(" -> ", path)}, cost {dist["Keep"]}");settle Camp at 0
relax Camp->Bridge: inf -> 4
relax Camp->Ford: inf -> 2
settle Ford at 2
relax Ford->Bridge: 4 -> 3
relax Ford->Hill: inf -> 9
relax Ford->Swamp: inf -> 5
settle Bridge at 3
relax Bridge->Mill: inf -> 8
settle Swamp at 5
relax Swamp->Keep: inf -> 14
settle Mill at 8
relax Mill->Keep: 14 -> 11
settle Hill at 9
relax Hill->Tower: inf -> 13
settle Keep at 11
settle Tower at 13
Camp to Keep: Camp -> Ford -> Bridge -> Mill -> Keep, cost 11
The "settle" order is the order the animation turns nodes green, and the final path skips the tempting direct trail from Camp to Bridge.
Weighted terrain on a grid
Grid search works the same way: the edge cost is the cost of the cell you step into. On this map, . floor costs 1 and ~ mud costs 5. The short route along the top crosses four mud cells. The program runs BFS (which ignores costs) and Dijkstra on the same map and prints both results:
using System;
using System.Collections.Generic;
string[] map =
{
"##############",
"#S...~~~~...G#",
"#.##########.#",
"#.#........#.#",
"#.#.######.#.#",
"#...######...#",
"##############",
};
var start = (x: 1, y: 1);
var goal = (x: 12, y: 1);
var dirs = new (int dx, int dy)[] { (0, -1), (1, 0), (0, 1), (-1, 0) };
int Cost((int x, int y) c) => map[c.y][c.x] == '~' ? 5 : 1;
Show("BFS (fewest steps)", Search(useCosts: false));
Show("Dijkstra (lowest cost)", Search(useCosts: true));
(Dictionary<(int x, int y), (int x, int y)> cameFrom, int expanded) Search(bool useCosts)
{
var cameFrom = new Dictionary<(int x, int y), (int x, int y)> { [start] = start };
var best = new Dictionary<(int x, int y), int> { [start] = 0 };
var queue = new Queue<(int x, int y)>();
var pq = new PriorityQueue<(int x, int y), (int cost, int order)>(); // order breaks ties: first in, first out
int pushes = 0, expanded = 0;
queue.Enqueue(start);
pq.Enqueue(start, (0, pushes++));
while (useCosts ? pq.Count > 0 : queue.Count > 0)
{
(int x, int y) cur;
if (useCosts)
{
pq.TryDequeue(out cur, out var pri);
if (pri.cost > best[cur]) continue; // stale entry: a cheaper one was already used
}
else cur = queue.Dequeue();
expanded++;
if (cur == goal) break;
foreach (var (dx, dy) in dirs)
{
var next = (x: cur.x + dx, y: cur.y + dy);
if (map[next.y][next.x] == '#') continue;
int newCost = best[cur] + Cost(next);
if (useCosts ? best.TryGetValue(next, out int old) && old <= newCost : cameFrom.ContainsKey(next)) continue;
best[next] = newCost;
cameFrom[next] = cur;
if (useCosts) pq.Enqueue(next, (newCost, pushes++)); else queue.Enqueue(next);
}
}
return (cameFrom, expanded);
}
void Show(string title, (Dictionary<(int x, int y), (int x, int y)> cameFrom, int expanded) r)
{
var grid = Array.ConvertAll(map, row => row.ToCharArray());
int steps = 0, cost = 0;
for (var c = goal; c != start; c = r.cameFrom[c])
{
steps++;
cost += Cost(c);
if (c != goal) grid[c.y][c.x] = '*';
}
Console.WriteLine(quot;{title}: {steps} steps, cost {cost}, expanded {r.expanded}");
foreach (var row in grid) Console.WriteLine(" " + new string(row));
}BFS (fewest steps): 11 steps, cost 27, expanded 22
##############
#S**********G#
#.##########.#
#.#........#.#
#.#.######.#.#
#...######...#
##############
Dijkstra (lowest cost): 23 steps, cost 23, expanded 31
##############
#S...~~~~...G#
#*##########*#
#*#********#*#
#*#*######*#*#
#***######***#
##############
BFS walks straight through the mud: fewer steps, much higher cost. Dijkstra takes the long dry way round because 23 cost units beat 27. The guard following the Dijkstra path looks smarter, and nothing about the algorithm is "smart": the level designer painted the mud, and the search respected it.
Note: The
PriorityQueuein .NET doesn't support "decrease key", so the code pushes a node again whenever its cost improves and skips stale entries when they come out (pri.cost > best[cur]). This "lazy deletion" is the standard trick in games, and it's simpler and usually faster than a heap with decrease-key. .NET's queue also doesn't promise any order between equal priorities, so the insertion counter in the priority makes the result deterministic.
Dijkstra's limits and strengths
Dijkstra expands nodes in rings of equal cost around the start, in every direction, exactly like BFS does for steps. That's wasteful when you want one path to one goal, which is why A* Search adds a sense of direction. But the full flood is useful on its own:
| Use | How |
|---|---|
| Distances from one point to everything | run without an early exit; best holds every cost |
| Nearest of many targets (closest health pack, closest exit) | start from the agent, stop at the first target popped |
| One field for hundreds of units | run from the goal over the whole map: that's the integration field of Flow Fields |
| Danger-aware routes | add influence map values to the cell costs |
Every edge cost must be non-negative. A negative cost could make a settled node cheaper later, and the algorithm would be wrong. Games never need negative costs; give "attractive" cells a lower positive cost instead.
Test yourself
What is the only structural difference between BFS and Dijkstra's algorithm?
- Dijkstra uses a stack
- Dijkstra's frontier is a priority queue ordered by cost so far instead of a FIFO queue
- Dijkstra needs a heuristic
- Dijkstra only works on grids
In the grid example, why does BFS choose the path through the mud?
- Mud is cheaper
- BFS counts steps and ignores cell costs, and the mud route has fewer steps
- BFS has a bug
- The Dijkstra route is blocked
What does lazy deletion mean in a Dijkstra implementation?
- Nodes are deleted after the search
- When a node's cost improves it is pushed again, and outdated queue entries are skipped when popped
- Walls are removed lazily
- The path is built later