Dijkstra’s algorithm finds shortest paths by spreading out evenly in every direction, like ripples in a pond. When you only care about reaching one goal, much of that work is wasted. A* search (pronounced “A star”) adds a heuristic, a guess of the remaining distance, so it explores cells that look closer to the goal first. Games use it to move characters around maps, and route planners use the same idea. With a good heuristic, A* finds the same shortest path as Dijkstra while exploring far fewer cells.
In this lesson you will learn
- The cost function f = g + h
- The Manhattan distance heuristic on a grid
- Why A* expands fewer cells than Dijkstra
- Admissible heuristics and why they guarantee the shortest path
- Weighted A*: trading path quality for speed
You should know BFS and DFS, Dijkstra’s algorithm and heaps.
A* on a Grid
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define R 8
#define C 12
/* '#' = wall, S = start, G = goal */
const char *grid[R] = {
"S...#.......",
".##.#.####..",
".#..#....#..",
".#.###.#.#..",
".#.....#.#..",
".#####.#.##.",
".......#...G",
"..#.........",
};
int g[R][C], parent[R][C], closed[R][C], expanded;
int h(int r, int c, int gr, int gc) { return abs(r - gr) + abs(c - gc); } /* Manhattan */
/* Very small A*: picks the open cell with the lowest f = g + h by scanning.
(A real program would use a binary heap; see the heap lesson.) */
int astar(int sr, int sc, int gr, int gc, int useH) {
int open[R][C] = {0};
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) { g[r][c] = 1 << 30; closed[r][c] = 0; }
g[sr][sc] = 0; open[sr][sc] = 1; parent[sr][sc] = -1; expanded = 0;
int dr[] = {-1, 1, 0, 0}, dc[] = {0, 0, -1, 1};
for (;;) {
int br = -1, bc = -1, bestF = 1 << 30;
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++)
if (open[r][c]) {
int f = g[r][c] + (useH ? h(r, c, gr, gc) : 0);
if (f < bestF) { bestF = f; br = r; bc = c; }
}
if (br < 0) return -1; /* nothing left: no path */
open[br][bc] = 0; closed[br][bc] = 1; expanded++;
if (br == gr && bc == gc) return g[br][bc];
for (int k = 0; k < 4; k++) {
int nr = br + dr[k], nc = bc + dc[k];
if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
if (grid[nr][nc] == '#' || closed[nr][nc]) continue;
if (g[br][bc] + 1 < g[nr][nc]) {
g[nr][nc] = g[br][bc] + 1;
parent[nr][nc] = br * C + bc;
open[nr][nc] = 1;
}
}
}
}
int main(void) {
int sr = 0, sc = 0, gr = 6, gc = 11;
int lenD = astar(sr, sc, gr, gc, 0);
int expD = expanded;
int lenA = astar(sr, sc, gr, gc, 1);
printf("Dijkstra (no heuristic): length %d, cells expanded %d\n", lenD, expD);
printf("A* (Manhattan heuristic): length %d, cells expanded %d\n\n", lenA, expanded);
char out[R][C + 1];
for (int r = 0; r < R; r++) strcpy(out[r], grid[r]);
for (int p = parent[gr][gc]; p != -1 && p != sr * C + sc; p = parent[p / C][p % C])
out[p / C][p % C] = '*';
for (int r = 0; r < R; r++) printf("%s\n", out[r]);
return 0;
}
Output
Dijkstra (no heuristic): length 19, cells expanded 53
A* (Manhattan heuristic): length 19, cells expanded 38
S...#.......
*##.#.####..
*#..#....#..
*#.###.#.#..
*#.....#.#..
*#####.#.##.
*******#***G
..#...***...
- Each cell has three values. g is the real cost from the start so far. h is the heuristic guess from the cell to the goal. f = g + h estimates the length of the whole path through that cell.
- A* always expands the open cell with the smallest f. With
h = 0it becomes Dijkstra’s algorithm, which is how the program compares the two. - On a grid where you move up, down, left or right, the Manhattan distance
|r1 - r2| + |c1 - c2|is a natural heuristic. It is the distance if there were no walls. - Both versions find a path of length 19, but A* expands 38 cells instead of 53.
parentstores where each cell was reached from, so the path can be drawn backwards from the goal. The stars show the route.- To keep the code short, this version finds the smallest f by scanning the whole grid. That is fine for a tiny map but slow for large ones.
A Heap, and What Happens When h Is Too Big
#include <stdio.h>
#include <stdlib.h>
#define R 9
#define C 14
/* A small maze with several possible routes */
const char *grid[R] = {
"####.....#....",
"#..#.###......",
"#.............",
"#.#.###..###..",
"S.#.....#...#G",
"##.....###.#..",
"###.......#...",
"...#.#.###..#.",
"..#...#.##..#.",
};
/* Binary heap of (f, cell) pairs: the usual way to get the lowest f fast */
typedef struct { int f, cell; } Item;
Item heap[R * C * 4]; int hsize;
void hpush(int f, int cell) {
int i = hsize++;
heap[i] = (Item){ f, cell };
while (i > 0 && heap[(i - 1) / 2].f > heap[i].f) {
Item t = heap[i]; heap[i] = heap[(i - 1) / 2]; heap[(i - 1) / 2] = t; i = (i - 1) / 2;
}
}
Item hpop(void) {
Item top = heap[0]; heap[0] = heap[--hsize];
for (int i = 0;;) {
int l = 2 * i + 1, r = l + 1, m = i;
if (l < hsize && heap[l].f < heap[m].f) m = l;
if (r < hsize && heap[r].f < heap[m].f) m = r;
if (m == i) break;
Item t = heap[i]; heap[i] = heap[m]; heap[m] = t; i = m;
}
return top;
}
/* f = g + w * h. w = 0 is Dijkstra, w = 1 is A*, w > 1 is "weighted" A* */
void run(double w, int sr, int sc, int gr, int gc) {
int g[R * C], done[R * C] = {0}, expanded = 0;
for (int i = 0; i < R * C; i++) g[i] = 1 << 29;
hsize = 0;
g[sr * C + sc] = 0;
hpush(0, sr * C + sc);
int dr[] = {-1, 1, 0, 0}, dc[] = {0, 0, -1, 1};
while (hsize) {
int cell = hpop().cell;
if (done[cell]) continue; /* old, stale heap entry */
done[cell] = 1; expanded++;
int r = cell / C, c = cell % C;
if (r == gr && c == gc) break;
for (int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= R || nc < 0 || nc >= C || grid[nr][nc] == '#') continue;
int n = nr * C + nc;
if (g[cell] + 1 < g[n]) {
g[n] = g[cell] + 1;
int hv = abs(nr - gr) + abs(nc - gc);
hpush(g[n] + (int)(w * hv), n);
}
}
}
printf("w = %.0f: path length %2d, cells expanded %3d\n", w, g[gr * C + gc], expanded);
}
int main(void) {
run(0, 4, 0, 4, 13); /* Dijkstra */
run(1, 4, 0, 4, 13); /* A* with an admissible heuristic */
run(5, 4, 0, 4, 13); /* overweighted heuristic: faster, may not be shortest */
return 0;
}
Output
w = 0: path length 17, cells expanded 62
w = 1: path length 17, cells expanded 27
w = 5: path length 21, cells expanded 22
- This version keeps the open cells in a binary heap, so the cell with the smallest f is found in O(log n). A cell may be pushed more than once; the
donecheck skips stale copies. wmultiplies the heuristic: f = g + w × h. Withw = 0it is Dijkstra, and withw = 1it is normal A*.- A heuristic is admissible if it never overestimates the real remaining distance. Manhattan distance is admissible here, because walls can only make the trip longer. With an admissible heuristic, A* always finds a shortest path.
- With
w = 5, the heuristic overestimates. The search rushes towards the goal, expands only 22 cells, but returns a path of length 21 instead of 17. This is weighted A*: useful when a fast “good enough” path matters more than the best one.
| Moves allowed | Admissible heuristic |
|---|---|
| 4 directions (up, down, left, right) | Manhattan: dx + dy |
| 8 directions, diagonal costs √2 | Octile: max(dx, dy) + (√2 - 1) × min(dx, dy) |
| Any direction (open map) | Straight-line (Euclidean) distance |
| Road network | Straight-line distance divided by the top speed |
Common Mistakes
- Using a heuristic that overestimates while expecting the shortest path.
- Using Manhattan distance when diagonal moves are allowed, which can overestimate and break the guarantee.
- Stopping when the goal is first pushed into the open set, instead of when it is popped. A cheaper path to it may still be waiting.
- Forgetting to skip stale heap entries, which wastes time or expands a cell twice.
Practice Exercises
Exercise 1. Is h = 2 × Manhattan distance admissible on a 4-direction grid?
Show answer
No. In open space with no walls, the real distance equals the Manhattan distance, so doubling it overestimates. A* might then return a longer path.
Exercise 2. Write the octile heuristic in C for 8-direction movement.
Show answer
double octile(int r1, int c1, int r2, int c2) {
int dx = abs(c1 - c2), dy = abs(r1 - r2);
int lo = dx < dy ? dx : dy, hi = dx < dy ? dy : dx;
return hi + (sqrt(2.0) - 1) * lo;
}
Frequently Asked Questions
Is A* always faster than Dijkstra?
It never expands more cells when the heuristic is consistent, and it is usually much faster for a single goal. If the heuristic is always 0, A* is exactly Dijkstra. When you need distances to every node, plain Dijkstra is the right tool.
What is a consistent heuristic?
A heuristic is consistent if, for every step from a to b, h(a) is at most the step’s cost plus h(b). Consistent heuristics are also admissible, and with them each node needs to be expanded only once. Manhattan distance on a 4-direction grid is consistent.
Summary
- A* expands the node with the smallest f = g + h.
- With h = 0 it is Dijkstra; a good h focuses the search towards the goal.
- An admissible heuristic never overestimates and guarantees a shortest path.
- Weighting the heuristic speeds up the search but can return longer paths.
Next: Bloom Filter in C.
