Skip to the workspace
Pebellslearn by building
Shortest Paths at Scale  ›  Lesson

A* & Heuristic Search

A* & Heuristic Search 32 minSpend the search where the goal is

dsa / A* & Heuristic Search

Explore each scene at your own pace.

01 · One change to Dijkstra

One change to Dijkstra

A* & Heuristic Search

Definition
A* is a shortest-path search that orders its priority queue by f = g + h, where g is the cost so far and h is an estimate of the cost remaining. If h never overestimates the true cost (it is admissible), A* still returns a cheapest path.
In plain words
It is like Dijkstra with a sense of direction. Instead of exploring in every direction equally, you favour the roads that point towards the destination, as long as your estimate is never more pessimistic than the truth.

In short: A* is Dijkstra with one change: instead of ordering the heap by g (cost so far), it orders by f = g + h, where h is a heuristic guess of the cost still to go. As long as h never overestimates the true remaining cost (it is admissible), A* still finds the cheapest route, but expands far fewer junctions, because junctions pointing away from the goal get a large h and wait. An overestimating h breaks the guarantee and can return a worse route.

Two overlapping regions around a depot-to-harbour trip: a large pale circle labelled Dijkstra expanding equally in all directions, and a narrower green ellipse labelled A star stretched toward the goal

A driver at the depot, in the north-west corner of town, taps a pickup at the harbour in the south-east, and Meridian's live map has to answer at once. Dijkstra would get it right, but it settles junctions in rings around the start, spending as much effort away from the harbour as towards it. It has no idea where the harbour is.

You do. The harbour is south-east, and on a street grid you can't get there in fewer minutes than the number of blocks between you. A* is Dijkstra with that one piece of knowledge added, and it still guarantees the cheapest route.

One change to Dijkstra

Dijkstra pops the junction with the smallest g, the cost so far. A* pops the junction with the smallest

f(n)=g(n)+h(n)f(n) = g(n) + h(n)

where h is a heuristic: a guess of the cost still to go from n to the goal. Junctions in the goal's direction get small h and come off the heap first; junctions behind the start get large h and wait, often forever.

The guess has one job, and one rule. It must never overestimate the true remaining cost. A heuristic like that is called admissible. On Meridian's grid, every road takes at least as many minutes as the blocks it spans, so the block distance |x − gx| + |y − gy| is admissible: no real drive can beat it.

Here's A* on the town map, from the depot to the harbour. Each badge shows g + h once a junction has been reached, and the starting badges are just h:

watch it move · graph

A* orders its frontier by g + h. With a guess that never overshoots, it heads for the goal, expands five of nine junctions, and still finds the cheapest route.

Every junction starts with h, its block distance to the harbour. No road is faster than its blocks, so h never overshoots. 9 nodes, 12 edges, undirected.

1 / 6

The picture's claim is easy to check. Count how many junctions each search pops before it reaches the harbour:

What does this print?
import heapq
pos = {"depot": (0, 0), "mill": (2, 0), "quay": (4, 0), "west": (0, 2), "plaza": (2, 2),
       "east": (4, 2), "park": (0, 4), "market": (2, 4), "harbour": (4, 4)}
roads = [("depot", "mill", 2), ("mill", "quay", 3), ("depot", "west", 2), ("mill", "plaza", 2),
         ("quay", "east", 2), ("west", "plaza", 4), ("plaza", "east", 2), ("west", "park", 3),
         ("plaza", "market", 3), ("east", "harbour", 2), ("park", "market", 2), ("market", "harbour", 2)]
graph = {n: [] for n in pos}
for a, b, m in roads:
    graph[a].append((b, m))
    graph[b].append((a, m))

def expanded(weight):
    h = lambda n: weight * (abs(pos[n][0] - 4) + abs(pos[n][1] - 4))
    best, heap, done = {"depot": 0}, [(h("depot"), "depot")], []
    while heap:
        f, n = heapq.heappop(heap)
        if n in done:
            continue
        done.append(n)
        if n == "harbour":
            return len(done)
        for m, w in graph[n]:
            if best[n] + w < best.get(m, 99):
                best[m] = best[n] + w
                heapq.heappush(heap, (best[m] + h(m), m))

print(expanded(1), expanded(0))
Scene 1 of 10
Project context and further resources
You're building a piece ofMeridian — the router
This piece — astar_route(): Aims the search at the destination so a single route comes back in milliseconds.
Scenario A driver on the east side taps a pickup on the west side and expects a route before the screen finishes loading. Dijkstra would search the whole city in rings; the live router aims its search at the destination and still guarantees the cheapest route.
astar_route.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
astar_route(junctions, roads, start, goal) → dictThe cheapest route on the live map as {cost, path}, found with A*; cost -1 if there is no route.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.