Sub topic 4
Combining Both: f(n) = g(n) + h(n)
This chapter assumes you have read the previous two chapters on uniform-cost search (UCS) and greedy best-first search. It also assumes you can read Python that uses heapq, and that you know what a priority queue does. Here we join those two algorithms into a single evaluation function and look closely at what that function measures. The full A* procedure and its correctness proofs come in later chapters.
Two partial views of a node
Each of the earlier algorithms ranks the frontier using a single number, and each number leaves something out.
- g(n) is the cost of the cheapest path from the start to n found so far. It is exact for the path we have, but it says nothing about how far n is from the goal.
- h(n) is a heuristic estimate of the cheapest cost from n to the goal. It looks ahead, but it ignores how much we already paid to reach n.
UCS orders by g(n) alone. It expands outward in rings of equal cost and does not care which direction the goal lies in. Greedy best-first orders by h(n) alone. It heads straight at the goal and can commit to a path that was expensive to reach.
The evaluation function adds the two:
f(n) = g(n) + h(n)
Read f(n) as an estimate of the total cost of the cheapest solution that passes through n. The g term covers the part from the start to n, and the h term covers the part from n to the goal. Expanding the node with the smallest f means always working on the most promising complete route, based on what we know now.
| Algorithm | Priority key | What it uses | What it ignores |
|---|---|---|---|
| Uniform-cost search | g(n) | Cost already paid | Distance remaining |
| Greedy best-first | h(n) | Estimated cost remaining | Cost already paid |
| A* | g(n) + h(n) | Both | Nothing, if h is good |
One framework, three algorithms
All three algorithms share the same skeleton: a heap-based best-first search that only changes its priority key. Putting the key in a parameter makes the relationship concrete. If h(n) = 0 for every node, f reduces to g and A* becomes UCS. If you drop g from the key, you get greedy search.
The graph below has an optimal route S-B-C-D-G with cost 6. It also has a tempting shortcut through A that costs 7, and a dead-end branch through E and F that is cheap to enter.
This heuristic never overestimates the true remaining cost. For example, h(A) = 2 while the real cost from A is 5. F is a dead end, so no value of h(F) can overestimate its remaining cost.
import heapq
from itertools import count
graph = {
'S': [('A', 2), ('B', 1), ('E', 1)],
'A': [('G', 5)],
'B': [('C', 1)],
'C': [('D', 1)],
'D': [('G', 3)],
'E': [('F', 1)],
'F': [],
'G': [],
}
h = {'S': 4, 'A': 2, 'B': 5, 'C': 4, 'D': 3, 'E': 10, 'F': 10, 'G': 0}
def best_first(start, goal, priority):
tie = count()
open_heap = [(priority(0, start), next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
expanded = 0
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal], expanded
if node in closed:
continue
closed.add(node)
expanded += 1
for nxt, cost in graph[node]:
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(open_heap, (priority(new_g, nxt), next(tie), nxt))
return None, float('inf'), expanded
strategies = {
'greedy': lambda g_val, n: h[n],
'ucs': lambda g_val, n: g_val,
'astar': lambda g_val, n: g_val + h[n],
}
for name, key in strategies.items():
path, cost, expanded = best_first('S', 'G', key)
print(f"{name:7} path={'-'.join(path)} cost={cost} expanded={expanded}")Output:
greedy path=S-A-G cost=7 expanded=2
ucs path=S-B-C-D-G cost=6 expanded=7
astar path=S-B-C-D-G cost=6 expanded=5Each result shows a different trade-off:
- Greedy expands the fewest nodes, but it follows the low h(A) and returns a path that costs 7.
- UCS finds the optimal path, but it also expands E and F, a branch that leads nowhere, because they are cheap to reach.
- A* finds the optimal path and never touches E, because f(E) = 1 + 10 = 11 is never the smallest key.
Tracing f on the example
The table follows A* pop by pop. The "Pushed" column lists each successor with its (g, f) values.
| Step | Popped (g, f) | Pushed | Frontier after |
|---|---|---|---|
| 1 | S (0, 4) | A (2, 4), B (1, 6), E (1, 11) | A4, B6, E11 |
| 2 | A (2, 4) | G (7, 7) | B6, G7, E11 |
| 3 | B (1, 6) | C (2, 6) | C6, G7, E11 |
| 4 | C (2, 6) | D (3, 6) | D6, G7, E11 |
| 5 | D (3, 6) | G (6, 6) | G6, G7, E11 |
| 6 | G (6, 6) | goal | done |
A was expanded because its low h made f(A) = 4 look attractive. Once A's real successor showed up with f = 7, the search moved back to B. This is the main behavior of f: an optimistic estimate pulls the search toward a node, and the actual edge costs, added through g, correct the estimate when it turns out wrong.
Two things in the trace are worth noting:
- Along the optimal path the f-values go 4, 6, 6, 6, 6. They never decrease. With a consistent heuristic (covered in a later chapter), f is nondecreasing along any path. That property is why the first time the goal is popped, its cost is final.
- G appears in the frontier twice, with f = 7 and f = 6. The heap does not support "decrease key", so the code pushes a second entry. The cheaper entry is popped first. If the stale entry were ever popped, the closed-set check would skip it.
What a better h buys you
f(n) is a combination of a known cost and a guess. The quality of the guess controls how much work A* does.
- With h = 0, f = g and you have UCS. The search fans out in every direction.
- With h = h\ (the exact remaining cost), every node on an optimal path has f = C\, the optimal cost. Every node off that path has f > C\. A then expands only nodes on an optimal path, apart from tie-breaking effects.
- Between these extremes, a larger h that still never overestimates gives tighter f-values, so fewer nodes have f below C\*.
Informally, A expands every node with f(n) < C\, possibly some with f(n) = C\, and none with f(n) > C\. The heuristic changes which nodes fall below that line. The later chapters on admissibility, optimality, and dominance make these statements precise.
Common errors when computing f
Most bugs in hand-written A* come from computing f incorrectly or from using it at the wrong moment.
- Testing for the goal when it is pushed instead of when it is popped. In the example, G is first pushed with cost 7, through A. Returning at that point gives the wrong answer. An f-value is only final once its node reaches the front of the queue.
- Using step counts for g on a weighted graph. g must add up the real edge costs. If you count hops, f no longer measures solution cost.
- Mixing units. If edge costs are travel times in seconds and h is a straight-line distance in meters, then f = g + h is meaningless. Convert h into cost units first, for example distance divided by the maximum speed.
- Ordering by h and breaking ties with g. A tuple key such as
(h, g)is greedy search with a tie-breaker, not A*. The key must be the sumg + h. - Changing g without pushing a new entry. If you lower
g[nxt]but do not push(new_g + h(nxt), ...), the heap still holds the old, larger f, and the node may be expanded late or never. - Storing f and later reading it back as g. Keep g in its own dictionary. Recover it from there, not from the heap key.
Exercises
Exercise
The frontier holds node X with g = 7 and h = 2, and node Y with g = 3 and h = 7. Which node does UCS expand next, which does greedy best-first expand next, and which does A* expand next?
Show answer
UCS compares g and picks Y (3 < 7). Greedy compares h and picks X (2 < 7). A* compares f: f(X) = 9 and f(Y) = 10, so it picks X.
Exercise
In the example graph, change h(A) from 2 to 5, which is A's true remaining cost, and run A* again. Which nodes are expanded, and how many?
Show answer
After S is expanded, the frontier holds A with f = 7, B with f = 6, and E with f = 11. A pops B, then C (f = 6), then D (f = 6), then G (f = 6) as the goal. The expanded nodes are S, B, C, and D, four in total. A is never expanded because its f of 7 is higher than C = 6. The more accurate heuristic saved one expansion.
Exercise
Change best_first so that it returns as soon as the goal is pushed, instead of when it is popped. What path and cost does the A* strategy return on the example graph, and why?
Show answer
It returns S-A-G with cost 7. A has the lowest f (4) after S is expanded, so A is expanded next and pushes G with g = 7. The function returns at that point, before the cheaper route through B, C, and D has been explored. The goal test has to happen at pop time, when G's f-value is the smallest on the frontier.
Exercise
Explain why setting h(n) = 0 for every node turns A* into uniform-cost search, and state whether the result is still optimal.
Show answer
With h = 0, f(n) = g(n) + 0 = g(n), so the priority key is exactly the UCS key and nodes come off the heap in the same order. The result is still optimal, because a heuristic of 0 never overestimates. The search just gets no guidance toward the goal.