图论,循序渐进

免费课程
请先完成第 2 章测验

先检验第 2 章

完成第 2 章测验:共 10 题,答对 7 题即通过。可以无限次重做。

Guided by a Guess

第 3 章,第 4 课,共 4 课

A*: Dijkstra with a sense of direction.

本课为英语讲解。可在上方开启英文、阿拉伯文、德文、西班牙文或法文字幕。

文字版课程

阅读约 9 分钟以英文撰写。

In 1968, at the Stanford Research Institute, a robot called Shakey had to plan its own route through a suite of rooms. Its builders needed a search that would not waste time looking the wrong way. Dijkstra's algorithm settles every place closer than the goal, even the ones in the opposite direction.

Three researchers at the institute, Peter Hart, Nils Nilsson and Bertram Raphael, gave the search a sense of direction: a guess of the distance still to go. They called it A* (A star). This lesson covers how the guess works, why A* still finds the cheapest route, when a bad guess breaks it, and how a better guess saves work.

A blind search

Dijkstra settles vertices in order of their distance from the start. It knows exactly what it has paid, but nothing about where the goal is, so its frontier grows like a circle.

On lesson 10's map of the Netherlands, Dijkstra settles all fourteen cities before it reaches Groningen. A* settles only the six cities on the route.

Dijkstra settles 14 cities, A* only the 6 on the route.Dijkstra settles 14 cities, A* only the 6 on the route.

On a grid with walls, from the left edge to the right, Dijkstra expands 758 cells before it reaches the goal. Many of them lie behind the start, or far off to the sides. A good search should lean towards the goal.

f = g + h

A* ranks every frontier vertex by two numbers added together:

  • g(n): what the route to n has cost so far, exactly.
  • h(n): a guess (the heuristic) of what the rest, from n to the goal, will cost.

It always expands the vertex with the smallest f(n) = g(n) + h(n): the best estimate of a whole route that passes through n.

On the same grid, with h set to the number of steps left if there were no walls, A* expands only 220 cells and finds the same 43-step route.

Same grid, same route, 220 cells instead of 758.Same grid, same route, 220 cells instead of 758.

The two extremes are worth knowing:

  • With h = 0, A* is exactly Dijkstra.
  • Ignore g, and it becomes greedy best-first search: quick (153 cells here), but its route takes 61 steps instead of 43.

Run it by hand

The worked example from our guide has six vertices, from S to G, with a guess beside each one.

EdgeS-AS-BS-GA-CA-DB-DC-GD-G
Weight4320512763
VertexSABCDG
Guess h1198530
Expandg + h = fFrontier afterwards
S0 + 11 = 11B 11, A 13, G 20
B3 + 8 = 11D 13, A 13, G 20
D10 + 3 = 13G 13, A 13
G13 + 0 = 13goal reached

When D and A are tied at 13, the tie goes to the smaller guess: D. Through D the goal is reached for a total of 13, and when G comes off the frontier with f = 13, A* stops.

The route is S, B, D, G, costing 3 + 7 + 3 = 13, and vertex C was never even looked at. On the same graph, Dijkstra settles all six vertices, C included, before it reaches G.

The worked example: four expansions, and C is never generated.The worked example: four expansions, and C is never generated.

Still the cheapest

The guess must be admissible: it never overestimates the true cost to the goal, h(n) ≤ h*(n).

Why the first route to the goal is the cheapest. Suppose A* took the goal off the frontier at cost C, while a cheaper route of total C* < C existed.

  1. Some vertex n of that cheaper route is still on the frontier, reached at its exact cost g*(n) along that route.
  2. Its f is g*(n) + h(n) ≤ g*(n) + h*(n) = C*, because the guess does not overestimate.
  3. So f(n) ≤ C* < C, and n would have come off the frontier before the goal. Contradiction.

Any cheaper route leaves a vertex on the frontier with a smaller f.Any cheaper route leaves a vertex on the frontier with a smaller f.

A sharper guess never changes that answer. It only changes how much work is done to find it.

A bad guess

There is a catch. Most implementations never reopen a vertex once it has been expanded, just like Dijkstra. For that, admissible is not enough.

Here is a directed graph from our guide: S → A 1, S → B 2, A → C 1, B → C 1, C → G 10, with guesses S 0, A 11, B 5, C 0, G 0. Every guess is admissible (from A the goal really costs 11), but the guess at A is far too large next to C.

A* expands S, then B (f = 7), then C through B at g = 3, then A (f = 12). By now C is closed, so the cheaper way into C through A (g = 2) is ignored, and A* returns 13. The true cheapest route, S, A, C, G, costs 12.

Admissible but not consistent: A* returns 13 instead of 12.Admissible but not consistent: A* returns 13 instead of 12.

The fix is consistency:

Along every edge u → v, the guess may drop by at most the weight of that edge: h(u) ≤ w(u, v) + h(v).

Here h(A) = 11 but w(A, C) + h(C) = 1, so the guess is not consistent. With a consistent guess, every expanded vertex is final, and every consistent guess is also admissible. The original 1968 proof quietly relied on this property; a note in 1972 corrected it, and made clear that with an inconsistent guess, expanded vertices must be allowed to reopen.

Johnson's trick again. Replace each weight by w(u, v) + h(v) − h(u). A consistent guess makes every adjusted weight zero or more, and every route from S to G changes by the same amount, h(G) − h(S). So A* is exactly Dijkstra on the adjusted graph. On the worked example, Dijkstra with adjusted weights settles S, B, D, G, A*'s own order, and finds 13 − 11 = 2.

With adjusted weights, A* is Dijkstra.With adjusted weights, A* is Dijkstra.

Better guesses

Good guesses come from relaxing the problem: drop a rule, and solve what is left exactly.

  • On a grid that moves in four directions, ignore the walls and count the steps across plus the steps down (the Manhattan distance).
  • With diagonal steps that cost one, take the larger of the two.
  • With movement at any angle, take the straight-line distance.

On the 8 puzzle, one guess counts the misplaced tiles; another adds up how far each tile is from its home square. For this position they say 7 and 14, and the real answer is 22 moves.

Two admissible guesses for the 8 puzzle.Two admissible guesses for the 8 puzzle.

Both are admissible, but the larger guess knows more. With misplaced tiles, A* expands 5,118 positions; with the distances, only 364.

A guess of zero turns A* back into Dijkstra, and a perfect guess would walk straight to the goal. Every useful heuristic lives somewhere in between.

Cost and uses

In the worst case A* is no faster than Dijkstra, and it keeps its whole frontier in memory. On huge searches, memory runs out first.

Weighted A* multiplies the guess, for example f = g + 2h. It turns greedier and faster: on our grid it expands 148 cells, and its route may cost up to twice the best. Here it costs 45 instead of 43.

Weighted A*: fewer cells, a slightly longer route.Weighted A*: fewer cells, a slightly longer route.

A* and its variants guide characters in video games, plan the moves of robots, and, with guesses computed in advance, speed up route planning on road maps.

In Python, A* is Dijkstra's heap loop with the guess added to the priority. Ties go to the smaller guess, as in the worked example:

import heapq

def a_star(graph, h, start, goal):
    g = {start: 0}
    parent = {start: None}
    heap = [(h[start], h[start], start)]  # (f, h, vertex)
    closed = set()
    while heap:
        f, _, u = heapq.heappop(heap)
        if u == goal:
            path = []
            while u is not None:
                path.append(u)
                u = parent[u]
            return path[::-1], g[goal]
        if u in closed:
            continue
        closed.add(u)
        for v, w in graph[u]:
            if g[u] + w < g.get(v, float("inf")):
                g[v] = g[u] + w
                parent[v] = u
                heapq.heappush(heap, (g[v] + h[v], h[v], v))
    return None, float("inf")

graph = {"S": [("A", 4), ("B", 3), ("G", 20)], "A": [("S", 4), ("C", 5), ("D", 12)],
         "B": [("S", 3), ("D", 7)], "C": [("A", 5), ("G", 6)],
         "D": [("A", 12), ("B", 7), ("G", 3)], "G": [("S", 20), ("C", 6), ("D", 3)]}
h = {"S": 11, "A": 9, "B": 8, "C": 5, "D": 3, "G": 0}
a_star(graph, h, "S", "G")  # (['S', 'B', 'D', 'G'], 13)

Key ideas

  • A* ranks the frontier by f = g + h: the cost so far, plus a guess of the cost to go.
  • If the guess never overestimates (admissible), the first route to the goal is the cheapest. If it is also consistent, no vertex ever needs reopening.
  • A guess of zero gives Dijkstra. The better the guess, the fewer vertices A* expands.
  • That completes chapter 3: four ways to find shortest paths, each built for a different question.
AlgorithmQuestionNegative weightsTime
Dijkstraone start, every vertexnoO((V + E) log V)
Bellman-Fordone start, every vertexyesO(V · E)
Floyd-Warshallevery pairyesO(V³)
A*one start, one goalnodepends on the guess

Check yourself

1. In the worked example, what is f for A when it is first put on the frontier?

2. On a four-direction grid, the goal is 5 columns right and 3 rows down. What does the Manhattan guess say, and why is it admissible?

3. Is the guess h(S) = 11, h(B) = 8 consistent on the edge S-B of weight 3?

Practice on the platform

Our A* guide traces this example step by step and proves why it works. In the A* visualizer, import the example and run it from S to G: S, B, D and G at a cost of thirteen, the same route we found by hand.

下一课

课程内容

已看 0 / 20

第 1 章Graph Theory Foundations

第 2 章Exploring a Graph请先完成第 1 章测验

第 3 章Shortest Paths请先完成第 2 章测验

第 4 章Connecting Cheaply请先完成第 3 章测验

第 5 章Hard Problems请先完成第 4 章测验

第 6 章Network Flows请先完成第 5 章测验