8 Uniform Cost Search

function UCS(P = ⟨S, s₀, A, τ, c, G⟩):
    g(s) ← ∞  for all s ∈ S
    agenda ← {s₀}                     # agenda is a set
    while agenda ≠ ∅:
        C ← arg min_{s ∈ agenda} g(s)
        s' ← any element of C
        if s' ∈ G:                    # goal found?
            return "done"
        for a ∈ A:                    # expand s
            s'' ← τ(s', a)
            update g(s'')  (replace existing value if smaller)
            agenda ← agenda ∪ {s''}

Execution Example

  • Successors are Rimnicu (80) and Fagaras (99)

  • Rimnicu is selected for expansion

  • Successor is Pitesi (80+97=17780 + 97 = 177)

  • Least cost is now Fagaras

  • Successor is Bucharest (99+211=31099 + 211 = 310)

  • Pitesi now selected for expansion

  • Bucharest updated (80+97+101=27880 + 97 + 101 = 278)

  • Bucharest selected for expansion; goal reached with optimal path

Handwritten diagram