Uniform-cost and iterative deepening
Uniform-cost search (UCS) chooses the pending route with the smallest accumulated cost. Iterative deepening repeatedly runs depth-limited DFS with increasing move limits. Both are uninformed: neither uses a heuristic estimate of the remaining cost. They optimize different quantities. On the previous graph, the single move A→G costs 9, whereas A→C→G costs 4.
Uniform-cost search: priority is the cost so far
A priority queue returns the smallest priority rather than the oldest entry. The Python heapq module manages a min-heap, and itertools.count supplies a unique increasing tie-breaker so equal costs are processed in insertion order. Each entry holds cost, serial number and path. The best dictionary records the cheapest discovered route to each state. When a cheaper route appears, push it and leave the old entry in the heap; skip outdated entries when popped. Accept a goal only when its current best entry is removed, not when it first appears.
from heapq import heappush, heappopfrom itertools import count
def ucs(graph, start, goal): serial = count() heap = [(0, next(serial), [start])] best = {start: 0} while heap: cost, _, path = heappop(heap) state = path[-1] if cost != best[state]: continue if state == goal: return cost, path for neighbor, weight in graph[state].items(): candidate = cost + weight if neighbor not in best or candidate < best[neighbor]: best[neighbor] = candidate heappush(heap, (candidate, next(serial), path + [neighbor])) return None
graph = {"A": {"B": 2, "C": 2, "G": 9}, "B": {"A": 2, "D": 1}, "C": {"G": 2}, "D": {"G": 2}, "G": {}, "X": {}}print(ucs(graph, "A", "G"))print(ucs(graph, "A", "X"))Output: (4, ['A', 'C', 'G']) and None. After removing A at cost 0, the frontier contains B at 2, C at 2 and G at 9. B adds D at 3. C improves G to 4. D proposes G at 5, which is not an improvement. The valid G entry at cost 4 is removed before the old entry at 9. Returning when G was first generated would have incorrectly returned 9. A start equal to the goal yields cost 0.
When is UCS guaranteed to work?
For this finite graph, all weights are nonnegative integers, all endpoints exist and costs are additive. The search returns a minimum-cost path or None if unreachable. Zero-cost edges are fine: equal-cost repeats do not enter the heap. Negative edges invalidate the goal-on-pop guarantee; the code assumes rather than validates its input contract. On an infinite search space, finite branching and a positive lower bound on step costs are sufficient for completeness when a finite-cost solution exists. Without that bound, infinitely many cheaper routes can delay a goal forever. A finite graph with nonnegative costs does not require strictly positive weights. Heap implementations with parent pointers and lazy duplicate entries commonly use O((V+E) log(V+E)) time and O(V+E) auxiliary storage; copying paths here adds overhead.
Depth-limited search and iterative deepening
A depth limit restricts the number of moves rather than energy. Depth-limited DFS explores only paths within the limit. It reports found for a goal, cutoff when a permitted continuation would exceed the limit, and failure when all allowed simple paths are exhausted. Test the goal first so a goal at exactly the limit succeeds. Use the current path to prevent cycles; do not use one global seen set, because a state first reached by a long route might later be reached with more remaining depth. Iterative deepening tries limits 0, 1, 2 and so on, rebuilding the search each time.
def depth_limited(graph, start, goal, limit): def visit(path, remaining): state = path[-1] if state == goal: return "found", path neighbors = [n for n in graph[state] if n not in path] if remaining == 0: return ("cutoff" if neighbors else "failure"), None cutoff = False for neighbor in neighbors: status, result = visit(path + [neighbor], remaining - 1) if status == "found": return status, result if status == "cutoff": cutoff = True return ("cutoff" if cutoff else "failure"), None if limit < 0: raise ValueError("limit must be nonnegative") return visit([start], limit)
def iterative_deepening(graph, start, goal): for limit in range(len(graph)): status, path = depth_limited(graph, start, goal, limit) if status == "found": return path if status == "failure": return None return None
graph = {"A": {"B": 2, "C": 2, "G": 9}, "B": {"A": 2, "D": 1}, "C": {"G": 2}, "D": {"G": 2}, "G": {}, "X": {}}print(depth_limited(graph, "A", "G", 0))print(depth_limited(graph, "A", "G", 1))print(iterative_deepening(graph, "A", "G"))print(iterative_deepening(graph, "A", "X"))The four lines are ('cutoff', None), ('found', ['A', 'G']), ['A', 'G'] and None. At limit zero A is not a goal and has available continuations. At limit one, B and C cannot reach G without another move, but direct G succeeds. For X, no path exists. This finite implementation stops after at most V−1 edges because any reachable goal has a simple path of that length or less. The recursive teaching code is for tiny graphs only; deep graphs can hit Python’s recursion limit. It assumes nonnegative integer depth limits.
Choose an algorithm for the objective
Use BFS or iterative deepening when minimizing moves. Use UCS for varying nonnegative energy costs. Use DFS for reachability when solution quality is not the main objective. Depth-limited DFS can respect a fixed move budget, but a cutoff is not proof of impossibility. Iterative deepening revisits shallow paths and may be slower on narrow chains; it trades repeated work for a smaller depth-first frontier. In a regular tree with branching factor b>1 and shallowest goal depth d, repeated depth-first passes take O(b^d) time and standard depth-first storage O(bd) or less depending on successor generation. The sample copies paths and neighbor lists, so its memory is not exactly that bound. On a finite graph, the simple-path enumeration may still be exponential. None of these guarantees covers a model that changes during search.
Practice
Change A→G to cost 1. Predict the new UCS result and explain why BFS does not change. Next, change the goal to X and distinguish cutoff at depth 0 from exhaustion at depth V−1. Verify results by summing corridor costs and comparing endpoints; never treat a returned route as a real-world action authorization. Next chapter adds a heuristic estimate and introduces adversarial search.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Uniform-cost and iterative deepening — understanding check
Apply uninformed search to finite directed graphs and reason about algorithm guarantees.
Which route minimizes energy in the original graph?
In UCS on the declared nonnegative-cost graph, when may the algorithm accept a goal as minimum-cost?
At depth limit zero, A is not a goal and has legal successors. What does the lesson function report?
Why can a global seen set break depth-limited DFS?
Which additional condition is sufficient for UCS completeness on a finitely branching infinite search space with a finite-cost solution?