Sub topic 2
Uniform-Cost Search: Expanding by Cost So Far
This chapter assumes you can read Python, know what a weighted graph is, and have used breadth-first search (BFS) and a priority queue. We build on the previous chapter's framing of pathfinding as a weighted graph.
From BFS to Cost Ordering
BFS expands nodes in order of the number of edges from the start. When every edge costs the same, that order is also the order of path cost. When edges have different weights, BFS can find a path with few edges that still costs more than a longer path.
Uniform-cost search (UCS) fixes this. It always expands the frontier node with the lowest g(n), the cost of the cheapest path found so far from the start to n. On a graph with an explicit start node, UCS is Dijkstra's algorithm with an early stop at the goal.
A Small Example
BFS reaches D through A→B→D at cost 6. The cheapest path is A→B→C→D at cost 4.
The Algorithm
import heapq
def ucs(start, goal, neighbors):
frontier = [(0, start)]
g = {start: 0}
parent = {start: None}
closed = set()
while frontier:
cost, node = heapq.heappop(frontier)
if node in closed:
continue # stale entry: a cheaper copy was already expanded
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], cost
closed.add(node)
for nxt, w in neighbors(node):
new_g = cost + w
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(frontier, (new_g, nxt))
return None, float('inf')
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('C', 2), ('D', 5)],
'C': [('D', 1)],
'D': [],
}
print(ucs('A', 'D', lambda n: graph[n])) # (['A', 'B', 'C', 'D'], 4)Tracing the Run
| Step | Popped (g, node) | Action | Frontier after |
|---|---|---|---|
| 1 | (0, A) | push B=1, C=4 | (1,B), (4,C) |
| 2 | (1, B) | improve C to 3, push D=6 | (3,C), (4,C), (6,D) |
| 3 | (3, C) | improve D to 4 | (4,C), (4,D), (6,D) |
| 4 | (4, C) | C already closed, skip | (4,D), (6,D) |
| 5 | (4, D) | goal, return | — |
Python's heapq has no decrease-key operation, so the code pushes a new entry instead and skips the old ones when they are popped. This "lazy deletion" pattern is the usual approach.
Why It Is Optimal
With non-negative edge weights, the g-values popped from the heap never decrease. When a node is popped for the first time, any other path to it would have to pass through a frontier node whose g is already at least as large. So the first pop of the goal gives its cheapest path.
Common Errors
- Testing for the goal when pushing instead of when popping. In step 2, D is pushed with cost 6. Returning at that point gives the wrong answer.
- Forgetting to skip stale entries. The answer stays correct, but nodes get re-expanded and the run wastes work.
- Negative edge weights. They break the non-decreasing order, and UCS can return a path that is not the cheapest. Use Bellman–Ford for those graphs.
Cost
With a binary heap, UCS runs in O((V + E) log V) time in the worst case. Lazy deletion can put up to E entries in the heap at once.
Exercise
Change the edge C→D to cost 3 and run ucs('A', 'D', ...). What path and cost does it return, and which node is popped as a stale entry?
Show answer
Both A→B→C→D and A→B→D now cost 6. The stale entry is (4, C), popped after (3, C). D is first pushed with g=6 from B. The later candidate from C also costs 6, which is not strictly less, so parent[D] stays B. The function returns (['A', 'B', 'D'], 6).
Exercise
Why does UCS behave exactly like BFS when every edge costs 1?
Show answer
When every edge costs 1, g(n) equals the number of edges from the start. Ordering the frontier by g then expands nodes level by level, which is the same order BFS uses.