concept
Uniform-cost and iterative deepening
UCS orders routes by cumulative cost; finite nonnegative graphs permit goal-on-pop optimality. Iterative deepening increases a depth limit to find a minimum-move route. Cutoff differs from failure. These are teaching interfaces.
Formal Syntax & Structure
artificial-intelligence syntaxartificial-intelligence
ucs(graph, start, goal) → (cost, path) or None; depth_limited(graph, start, goal, limit) → (status, path)Working Example
Example Snippetartificial-intelligence
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"))