Sub topic 2
Uniform-Cost Search: Expanding by Cost So Far
This chapter assumes you can read Python, know what a weighted graph is, have used breadth-first search (BFS), and understand how a binary heap supports push and pop-min in O(log n). The previous chapter framed pathfinding as a search over a weighted graph of states. This chapter covers the first algorithm that searches that graph for the cheapest path: uniform-cost search (UCS).
The Core Idea: Always Expand the Cheapest Frontier Node
BFS expands nodes in order of how many edges they are from the start. That order gives the cheapest path only when every edge has the same cost. Once edges have different weights, a path with fewer edges can cost more than a path with many edges.
UCS fixes this by ordering the frontier by g(n), the total cost of the best path found so far from the start to node n. On every iteration it removes the frontier node with the smallest g and expands it, which means it generates that node's neighbors and records their costs.
The frontier is the set of nodes that have been generated but not yet expanded. In UCS it is a priority queue keyed on g. The expanded set (often called the closed set) holds nodes whose cheapest cost is already final.
The key invariant is:
- When UCS pops node n from the priority queue for the first time, g(n) equals the true least cost from the start to n.
This holds as long as every edge cost is non-negative. Any other path to n has to leave the expanded region through some frontier node m with g(m) ≥ g(n). Extending that path with non-negative edges cannot make it cheaper than g(m), so it cannot beat g(n).
A Worked Example
Consider this graph, where S is the start and G is the goal.
The direct edge S→G uses one hop but costs 10. The path S→A→B→G uses three hops but costs 3. BFS would reach G first through the direct edge. UCS proceeds like this:
| Step | Popped (g) | Pushed or updated | Frontier after step |
|---|---|---|---|
| 1 | S (0) | A=1, G=10 | A(1), G(10) |
| 2 | A (1) | B=2 | B(2), G(10) |
| 3 | B (2) | G=3 (improves on 10) | G(3), G(10) |
| 4 | G (3) | goal popped, stop | G(10) is left, stale |
In step 3 the frontier holds two entries for G. That is deliberate, and the implementation section explains why.
Implementation
The implementation below uses Python's heapq. It pushes a new entry whenever it finds a cheaper path to a node and skips outdated entries when they are popped. This technique is called lazy deletion.
import heapq
from itertools import count
def ucs(start, goal, neighbors):
"""Return (path, cost) of a least-cost path, or (None, inf).
neighbors(node) must yield (next_node, edge_cost) pairs
with edge_cost >= 0.
"""
tie = count() # breaks ties so nodes are never compared
frontier = [(0, next(tie), start)]
g = {start: 0}
parent = {start: None}
expanded = set()
order = [] # expansion order, for inspection
while frontier:
cost, _, node = heapq.heappop(frontier)
if node in expanded: # stale entry: a cheaper copy was already expanded
continue
if node == goal: # goal test when popped, not when generated
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], cost, order
expanded.add(node)
order.append(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, next(tie), nxt))
return None, float('inf'), order
graph = {
'S': [('A', 1), ('G', 10)],
'A': [('B', 1)],
'B': [('G', 1)],
'G': [],
}
path, cost, order = ucs('S', 'G', lambda n: graph[n])
print(path) # ['S', 'A', 'B', 'G']
print(cost) # 3
print(order) # ['S', 'A', 'B']Several design choices in this code matter.
- The tie counter. Python compares tuples element by element. If two entries have equal cost,
heapqwould compare the nodes next, and that raises an error for types that cannot be ordered. The counter makes every tuple unique before the node is reached. neighborsas a function. The graph does not need to exist in memory. A grid, a puzzle, or a road network can produce successors on demand.gandparentare updated together. The parent pointer always matches the best known cost, so rebuilding the path by following parents gives the cheapest path.
Why lazy deletion instead of decrease-key
Textbook Dijkstra uses a decrease-key operation to lower a node's priority in place. heapq has no decrease-key, and writing one requires tracking each node's index in the heap. Pushing a duplicate is simpler. The cost is that the heap can hold up to one entry per edge relaxation, so its size is O(E) instead of O(V). Since log E ≤ 2 log V, this changes the running time by at most a constant factor.
When to Test for the Goal
UCS must check for the goal when the goal is popped, not when it is generated. In the example, G is generated in step 1 with g=10. Stopping there would return the 10-cost path. G is only known to be optimal when it reaches the front of the queue, because by then every cheaper frontier node has been expanded.
BFS can test at generation time because, with unit costs, the first time a node is generated is always through a shortest path. This shortcut is one of the most common bugs when people adapt BFS code into UCS.
How UCS Relates to BFS and Dijkstra
| Property | BFS | UCS | Dijkstra (classic) |
|---|---|---|---|
| Frontier order | Edge count (FIFO queue) | g(n) (priority queue) | g(n) (priority queue) |
| Optimal for | Unit costs only | Non-negative costs | Non-negative costs |
| Goal test | At generation is safe | At expansion | No single goal, usually |
| Initial setup | Start only | Start only | Often all nodes set to infinity |
| Works on implicit or infinite graphs | Yes | Yes | Not as usually written |
| Output | One path | One path | Shortest-path tree to all nodes |
With all edge costs equal, UCS expands nodes in the same layered order as BFS, but pays O(log n) per heap operation instead of O(1). UCS and Dijkstra's algorithm are the same algorithm. The difference is framing. Dijkstra is usually presented as computing distances to every vertex of a known graph. UCS stops at a goal and generates nodes lazily, so it can run on graphs too large to list in advance.
Complexity
On an explicit graph with V nodes and E edges, the lazy-deletion version runs in O(E log E), which is O(E log V), and uses O(V + E) memory in the worst case.
For implicit graphs, a more useful bound uses the branching factor b, the optimal cost C, and the smallest edge cost ε > 0. UCS may explore every path whose cost is below C, and those paths can be up to about C/ε edges long. That gives O(b^(1 + ⌊C/ε⌋)) time and space. When many edges are cheap compared with C*, this can be much worse than BFS's O(b^d), because UCS explores large numbers of cheap, short-range paths before it commits to expensive edges.
This is the weakness the rest of the tutorial addresses. UCS knows only the cost paid so far. It spreads out evenly in every direction, including directly away from the goal.
Edge Cases and Failure Modes
Negative edge costs
The invariant depends on non-negative edges. With a negative edge, a node can be expanded and finalized before a cheaper path to it is discovered. Graphs with negative edges need Bellman–Ford, or Johnson's reweighting if you need repeated queries.
Zero-cost edges
On a finite graph with an expanded set, zero-cost edges are fine and UCS stays optimal. On an infinite graph, or in a tree search with no expanded set, a zero-cost cycle can keep producing new entries at the same g forever. Completeness requires every edge cost to be at least some ε > 0.
Unreachable goal
If the goal cannot be reached, UCS expands every node reachable from the start before it returns failure. On a large map that is expensive. If you can check reachability cheaply, for example with connected-component labels on a static map, do it first.
Exercise
The graph has edges S→A (cost 2), S→B (cost 3), and B→A (cost −2). Run the ucs function above with goal A. What does it return, and what is the true least cost?
Show answer
UCS pops S, pushes A=2 and B=3, then pops A at cost 2 and returns path S→A with cost 2. The true least cost is 1, through S→B→A. The negative edge breaks the invariant that a node's cost is final when it is popped.
Exercise
A programmer moves the goal check into the neighbor loop, returning as soon as nxt == goal. On the four-node example graph in this chapter, what cost does the modified code return?
Show answer
It returns 10. When S is expanded, it generates G through the direct edge and returns immediately, before discovering the path S→A→B→G with cost 3.
Exercise
On a 4-connected grid where every move costs 1, UCS and BFS find paths of the same cost. Give one reason to still prefer BFS on this grid, and one situation that would make you switch to UCS.
Show answer
BFS uses a FIFO queue with O(1) operations, so it avoids the O(log n) heap cost and is simpler. Switch to UCS when moves have different costs, for example terrain penalties or diagonal moves that cost sqrt(2).