Uniform-cost search
一致代价搜索
Find least-cost paths with nonnegative edges, understand why a discovered goal is not final, and implement a priority queue safely.
uniform-cost-searchSeeing the destination is not enough
From S, a direct road to G costs 8. Another road goes to A for cost 1, and A connects to G for cost 1. A search that returns as soon as it first sees G could report cost 8 and miss the route costing 2.
Uniform-cost search, or UCS, orders its frontier by accumulated route cost , rather than by edge count. It expands the cheapest current route first. With nonnegative edges, a goal becomes safe to return when its best current entry is removed from the priority queue—not merely when the goal is first generated.
Why the cheapest unsettled route can be finalized
Maintain a tentative best distance to each discovered state. When expanding , inspect an outgoing edge with cost and relax its endpoint:
A successful improvement updates the predecessor and schedules the new distance. Consider the state removed with minimum nonstale cost. If a cheaper route to it existed, take the first not-yet-finalized vertex on that route. Its predecessor has already been finalized, so relaxation would have placed a route to that vertex in the queue. Because the remaining edges are nonnegative, this queued cost would be no larger than the supposedly cheaper full route. It should have been removed before , contradicting the queue order.
This is the shortest-path principle in Problem 2 of Dijkstra’s 1959 paper. The paper’s Problem 1 concerns a different task, a minimum spanning tree; those two objectives should not be conflated. Dijkstra, pp. 270–271
UCS is commonly presented as goal-directed search over an implicit state space. Dijkstra’s algorithm commonly computes shortest distances from a source over an explicit graph. Their nonnegative-cost frontier principle is the same, while interfaces and stopping rules can differ. CS188, Uninformed Search
Leave old heap entries in place, then skip them
A binary heap does not need a custom decrease-key operation for this small implementation. Push a new entry whenever a distance improves and ignore an old entry if its distance no longer matches the stored best distance. A counter breaks priority ties, allowing state IDs that cannot be ordered against one another.
The complete program validates all supplied edges before searching. This matters because returning a goal early must not hide a negative edge elsewhere in the input. It permits zero-cost edges and cycles, accepts only strict distance improvements, and rejects nonfinite accumulated costs. AIMA offers a different priority-queue implementation of the same search principle. AIMA Python, uniform_cost_search
import heapq
import itertools
import math
def ucs(graph, start, goal):
for edges in graph.values():
for _,cost in edges:
if not math.isfinite(cost) or cost < 0:
raise ValueError("finite nonnegative edge costs required")
ticket = itertools.count()
heap = [(0, next(ticket), start)]
best, parent = {start:0}, {start:start}
while heap:
cost, _, u = heapq.heappop(heap)
if cost != best[u]:
continue
if u == goal:
path = [u]
while path[-1] != start:
path.append(parent[path[-1]])
return cost, path[::-1]
for v,edge_cost in graph.get(u, []):
candidate = cost+edge_cost
if not math.isfinite(candidate):
raise ArithmeticError("path cost exceeds float range")
if candidate < best.get(v, math.inf):
best[v], parent[v] = candidate, u
heapq.heappush(heap, (candidate, next(ticket), v))
return None
graph = {'S':[('G',8),('A',1)], 'A':[('G',1),('S',0)]}
assert ucs(graph,'S','G') == (2,['S','A','G'])
assert ucs(graph,'S','S') == (0,['S'])
assert ucs(graph,'S','missing') is None
assert ucs({'S':[('S',0),('G',1)]},'S','G')[0] == 1
mixed = {'S':[(0,1),('A',1)], 0:[('G',1)], 'A':[('G',2)]}
assert ucs(mixed,'S','G') == (2,['S',0,'G'])
try:
ucs({'S':[('G',1)],'unused':[('G',-1)]},'S','G')
except ValueError:
pass
else:
raise AssertionError("negative edge accepted")
On a finite graph with vertices and edges, this lazy heap can store entries. Including validation and reconstruction, its worst-case time is with expected constant-time dictionary operations, and extra space is . An indexed heap supporting decrease-key gives a different bound, usually time and frontier bookkeeping. Do not quote that memory bound for a heap retaining stale entries.
Nonnegative is enough for a finite graph, not every infinite space
For a finite graph with duplicate handling, zero-cost cycles do not invalidate UCS. In the implementation, an equal-cost return to a vertex never improves its distance, so it does not schedule another entry.
For an infinite state space, nonnegative costs alone do not guarantee finding a finite-cost goal. Imagine an endless chain of new zero-cost states and a goal reachable from the start for cost 1. The queue can keep selecting zero-cost states forever. Finite branching, terminating successor generation, and a positive lower bound on edge costs give a standard completeness condition for a reachable goal of finite optimal cost: only finitely many depths can stay below that cost.
Negative edges break the finalization proof because a later edge can lower the cost of a route that currently looks expensive. Use an algorithm with suitable assumptions, such as Bellman–Ford for finite graphs with negative edges, and handle reachable negative cycles explicitly. Floating-point costs introduce rounding: this example compares the arithmetic it computes, not exact real-number path sums. Integer units are preferable when the problem naturally permits them.
Locate the safe stopping point
- Why not return G when expanding S in the opening example? Answer: the direct cost 8 is tentative; expanding A later improves it to 2.
- What is the purpose of the heap counter? Answer: it breaks equal-priority ties without comparing arbitrary vertex IDs.
- Does a zero-cost self-loop cause endless insertions here? Answer: no. It produces an equal distance, and only strict improvements are inserted.
- Why does the infinite zero-cost chain defeat a simple completeness claim? Answer: infinitely many distinct states can stay cheaper than the goal, so duplicate detection cannot exhaust them.
From cost-only search to informed search
A* adds an estimate of remaining cost to UCS’s accumulated cost. Setting that estimate to zero recovers the UCS ordering. This makes UCS a useful reference when checking an A* implementation: on small nonnegative graphs, compare returned costs against UCS before attributing differences to heuristic quality. Keep path cost, expanded states, queue size, and wall time as separate measurements.
Make a prediction, then check
With nonnegative edges, when may UCS safely return a goal?
Learning objectives
- Prove finalization of minimum-cost queue entries with nonnegative edges.
- Implement a lazy priority queue and check zero-cost cycles, stale entries, and rejection of negative edges.
Prerequisites & connections
Explore related knowledge →References
- A Note on Two Problems in Connexion with Graphs
Edsger W. Dijkstra · 1959 - CS188 Textbook — Uninformed Search
UC Berkeley CS188 course contributors - AIMA Python — search algorithms (commit f104e03, 2026-06-30)
AIMA Python contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- On 60 seeded nonnegative graphs, every target matched the least cost from exhaustive simple paths; returned paths were recalculated edge by edge.
- Checked that goal generation cannot terminate early, stale heap entries, zero-cost cycles, mixed-vertex ties, and rejection of unvisited negative edges; complexity reflects lazy-heap storage.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- A Note on Two Problems in Connexion with Graphs · Problem 2, printed pp.270–271: tentative routes, improvement, and minimum-distance finalization
- CS188 Textbook — Uninformed Search · §1.3.3: priority by path cost; finite and infinite-state assumptions clarified in article
- AIMA Python — search algorithms (commit f104e03, 2026-06-30) · uniform_cost_search and best_first_graph_search, fixed commit f104e03
Related topics