Sub topic 3
Greedy Best-First Search: Expanding by Estimated Distance
The previous chapter's uniform-cost search (UCS) orders the frontier by g(n), the cost already paid to reach a node. It never considers where the goal is. Greedy best-first search does the opposite. It orders the frontier only by h(n), an estimate of the cost still to go, and ignores the cost already paid. This chapter shows how that change speeds up search, why it gives up optimality, and when its completeness also fails.
This chapter assumes you can read Python, know what a weighted graph is, and have seen breadth-first search and binary heaps (Python's heapq).
The Heuristic Function
A heuristic is a function h(n) that estimates the cost of the cheapest path from node n to the goal. It works from information about the problem that the graph alone does not give you, such as coordinates on a map. Two properties matter throughout this tutorial:
- h(goal) = 0 for every reasonable heuristic.
- h is only an estimate. It can be too low, too high, or exact, and greedy search trusts it fully.
On a road map, the straight-line distance to the destination is the classic heuristic. On a grid, Manhattan distance plays the same role. Later chapters cover how to pick and design heuristics. Here the heuristic is treated as a given.
The Algorithm
Greedy best-first search keeps a priority queue of frontier nodes keyed by h(n). On each step it removes the node that looks closest to the goal, stops if that node is the goal, and otherwise adds the node's unvisited neighbors to the queue.
import heapq
from itertools import count
def greedy_best_first(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), start)]
parent = {start: None}
g = {start: 0}
closed = set()
expanded = 0
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node in closed:
continue
closed.add(node)
expanded += 1
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal], expanded
for nxt, cost in neighbors(node):
if nxt not in parent:
parent[nxt] = node
g[nxt] = g[node] + cost
heapq.heappush(open_heap, (h(nxt), next(tie), nxt))
return None, float('inf'), expandedSome details in this code are worth noticing:
- The heap key is
h(nxt)alone.gis tracked only so we can report the cost of the path found. It plays no part in ordering. - A neighbor's parent is set once, on first discovery. Since priority never depends on g, finding a cheaper route to a node later does not change its place in the queue. UCS and A* update parents when they find a cheaper g. Greedy search usually does not bother.
- The counter breaks ties. When two nodes have equal h, the one pushed first comes out first, and
heapqnever has to compare the node objects themselves. - The closed set prevents re-expansion. Without it, greedy search can loop forever, as shown below.
A Worked Example Where Greedy Search Goes Wrong
Consider this small graph. Edge labels are step costs, and each node shows its heuristic value.
graph = {
'S': [('A', 1), ('B', 2)],
'A': [('G', 10)],
'B': [('C', 2)],
'C': [('G', 2)],
'G': [],
}
h_table = {'S': 5, 'A': 1, 'B': 4, 'C': 2, 'G': 0}
path, cost, expanded = greedy_best_first(
'S', 'G', lambda n: graph[n], lambda n: h_table[n])
print(path, cost, expanded) # ['S', 'A', 'G'] 11 3Here is the trace:
| Step | Popped | h | Pushed | Frontier after (h) |
|---|---|---|---|---|
| 1 | S | 5 | A, B | A(1), B(4) |
| 2 | A | 1 | G | G(0), B(4) |
| 3 | G | 0 | none | goal reached |
Greedy search returns S → A → G with cost 11. The optimal path S → B → C → G costs 6. UCS on the same graph expands S, A, B, C, G (five nodes) and returns the cost-6 path. Greedy expanded only three nodes, but its answer costs almost twice as much.
Properties
| Property | Greedy best-first | Uniform-cost search |
|---|---|---|
| Priority key | h(n) | g(n) |
| Optimal | No | Yes (non-negative costs) |
| Complete on finite graphs | Yes, with a closed set | Yes |
| Complete on infinite graphs | No | Yes, if every step costs at least some ε > 0 |
| Worst-case time and space | O(b^m) | O(b^(1 + C*/ε)) |
| Typical behavior with a good h | Very few expansions | Expands every node cheaper than the goal |
In the table, b is the branching factor, m is the maximum depth of the search space, and C* is the optimal cost. The worst case for greedy search depends on m rather than on the solution depth, because a misleading heuristic can send the search to the deepest parts of the space before it turns back. With a good heuristic the actual number of expansions is often close to the length of the path it returns. That speed is the reason people use it.
Failure Mode: Loops Without a Closed Set
Suppose S has neighbors A (h = 1) and C (h = 5), C leads to the goal, and A's only neighbor is S (h = 3). If you implement greedy search without a closed set (tree search), it pops S, then A, which pushes S again. It pops S, which pushes A again, and the cycle never ends. C, with h = 5, never reaches the front of the queue. The closed set breaks the cycle, and the search is then complete on any finite graph, because each node is expanded at most once.
Failure Mode: Infinite Spaces
On an infinite graph, a closed set is not enough. If there is an endless chain of new states whose h values keep shrinking, for example h = 1, 1/2, 1/3, and so on, greedy search follows that chain forever and never returns to the branch that holds the goal. UCS avoids this trap because g grows along any infinite path when every step has positive cost.
Failure Mode: Dead Ends on Grids
On grid maps, a concave obstacle such as a U-shaped wall that opens away from the goal is the standard trap. Manhattan distance pulls the search straight into the pocket. The search expands every cell inside before it reaches the cells around the rim. It still finds a path, but the path often hugs the wall and is longer than necessary. The number of expansions can also be much higher than the heuristic's usual speed suggests.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| No closed set | Program hangs on graphs with cycles | Track expanded nodes and skip them |
| Expecting the shortest path | Paths that detour or have high cost | Use UCS or A* when cost matters |
| Pushing tuples without a tie counter | `TypeError` when nodes are not comparable | Add `next(tie)` as the second key |
| Choosing h with the wrong scale | h ranks nodes in an order unrelated to how close they are | Make h estimate the same cost units as the edges |
| Reporting expansions as proof of quality | Few expansions taken to mean a good answer | Measure path cost separately |
When Greedy Best-First Search Is the Right Tool
Use greedy search when any reasonable path will do and response time matters more than path quality. Examples include checking whether a goal is reachable at all, placing a quick first path before refining it, or running searches in a game loop where an agent can correct its course later. It is also a useful baseline: if A* expands far more nodes than greedy search on your maps, your heuristic may be weaker than it could be.
UCS uses only g(n) and greedy search uses only h(n). The first is optimal but blind to direction. The second is guided but short-sighted. The next chapter combines the two in f(n) = g(n) + h(n).
Exercise
In the worked example, change h(A) from 1 to 7 and leave everything else the same. Trace greedy best-first search. Which path does it return, what does the path cost, and how many nodes does it expand?
Show answer
Expanding S pushes A(7) and B(4). B is popped and pushes C(2). C is popped and pushes G(0). G is popped. The path is S → B → C → G with cost 6, and four nodes are expanded (S, B, C, G). The heuristic now steers away from A, so greedy search happens to find the optimal path. Its ordering still ignores g, so this result is not guaranteed in general.
Exercise
A colleague proposes making greedy best-first search optimal by updating parent[nxt] whenever a cheaper g is found, as UCS does, while still ordering the heap by h(n). Does this guarantee an optimal path? Use the original example to justify your answer.
Show answer
No. In the original example, G is pushed when A is expanded and has h = 0, so it is popped next with g = 11. B and C are never expanded, and the cheaper route is never found. Updating parents only helps for routes the search actually discovers before it pops the goal, and with an h-only ordering the goal can come out first through an expensive route.
Exercise
Why does greedy best-first search's worst-case complexity depend on the maximum depth m of the space, while UCS's depends on the optimal cost C*?
Show answer
UCS expands nodes in order of g, so it never expands a node whose g is above C*. That limits how far it can go. Greedy search's ordering has no link to the path cost or depth, so a misleading heuristic can lead it down the deepest branches before it reaches the goal. In the worst case that means exploring on the order of b^m nodes.