learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Uniform Cost Search Visualizer

Always the cheapest frontier first

Expands the frontier vertex with the lowest path cost g first and tests the goal on expansion, so it finds the cheapest path from the start to the target

Time: O((V + E) log V)
Space: O(V)
Use Case: AI route planning, cheapest action sequences, the baseline for A*
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Uniform Cost Search (UCS)

Uniform cost search (UCS) is the uninformed search algorithm for finding the cheapest path from a start to a goal when steps have different costs. It is the version of Dijkstra's algorithm taught in artificial intelligence courses: it grows a frontier of vertices that have been reached but not expanded, and always expands the one with the lowest path cost g. Unlike breadth-first search it does not count steps but adds up their costs, so a long route of cheap roads can beat a short route of expensive ones.

How it works

The frontier is a priority queue ordered by g, the cost of the best route found so far, and starts with the start vertex at g = 0. Each step removes the cheapest vertex from the frontier. If it is the goal, the search stops, since no other frontier vertex can lead to a cheaper route. Otherwise the vertex joins the explored set, and each neighbour joins the frontier, or gets a lower g when this route to it is cheaper. The goal test happens on expansion, not when a vertex is first reached, and that is what makes the result optimal. With a binary heap the search takes O((V + E) log V) time. The example is the road map of Romania from Russell and Norvig's textbook, from Arad to Bucharest.

Applications

Uniform cost search plans routes on road networks and game maps, finds the cheapest sequence of actions in AI planning, and solves puzzles where moves have different costs. It is the baseline that A* improves on: A* adds a heuristic to the same frontier, and with h = 0 it is exactly uniform cost search. In an AI course UCS sits between breadth-first search and A*, which makes it a standard exam question.

Pseudocode

Uniform cost search is graph search with a priority queue ordered by path cost. Two details make it optimal: the goal test at expansion, and lowering a frontier entry when a cheaper route to it appears.

UniformCostSearch(start, goal):
    frontier = priority queue ordered by g
    frontier.add(start, g = 0)
    explored = {}
    while frontier is not empty:
        n = frontier.popLowestG()
        if n == goal: return the path to n
        explored.add(n)
        for each neighbour m of n:
            g2 = g(n) + cost(n, m)
            if m not in explored and m not in frontier:
                frontier.add(m, g2)
            else if m in frontier and g2 < g(m):
                frontier.lower(m, g2)
    return failure

When a vertex leaves the frontier its g is final: every other frontier vertex has a g at least as large, and with costs of 0 or more no route through them can come back cheaper. That is why the goal test waits for expansion. Testing the goal when it first joins the frontier would accept the first route found, not the cheapest.

Worked example, step by step

Find the cheapest route from Arad (A) to Bucharest (B) on the road map of Romania this page loads, with road lengths in km.

Example graph: Roads from Arad lead to Zerind (75), Timisoara (118) and Sibiu (140). From Sibiu, roads lead to Fagaras (99) and Rimnicu Vilcea (80). Fagaras reaches Bucharest directly (211), Rimnicu Vilcea through Pitesti (97, then 101).

  1. A, Z, T and S. Arad is expanded first, then Zerind (75), Timisoara (118) and Sibiu (140), in order of cost. Sibiu adds Rimnicu Vilcea at 220 and Fagaras at 239.
  2. Bucharest appears. Expanding Fagaras (239) puts Bucharest on the frontier at 239 + 211 = 450. The search does not stop, since a cheaper route may still exist.
  3. A cheaper route. Rimnicu Vilcea (220) adds Pitesti at 317. Expanding Pitesti finds Bucharest again at 317 + 101 = 418, so its entry drops from 450 to 418.
  4. The goal is expanded. After Craiova (366) and Drobeta (374), Bucharest has the lowest g, 418. Only now is it expanded, and the search ends.

The cheapest route is Arad, Sibiu, Rimnicu Vilcea, Pitesti, Bucharest, 418 km, and uniform cost search expanded 12 of the 20 cities. Had it stopped when Bucharest first appeared, it would have returned the 450 km route through Fagaras.

Complexity, and where it comes from

Time: O((V + E) log V) · Space: O(V)

Each vertex is expanded at most once and each edge is examined at most once from each end, and every frontier operation costs O(log V) with a binary heap, so a full run takes O((V + E) log V). AI textbooks state the cost for implicit search trees instead: O(b^(1 + ⌊C*/ε⌋)), where b is the branching factor, C* the cost of the best solution and ε the cheapest step cost. That bound shows the weakness of uniform cost search: with many cheap steps it explores a large region before it can reach an expensive goal.

When to use Uniform Cost Search (UCS), and when not to

Uniform cost search is one of four best-first searches that differ only in the priority they give the frontier.

AlternativePrefer it whenCost
Breadth-first searchAll steps cost the same: the fewest steps is the cheapest path, and a plain queue is enough.O(V + E)
Dijkstra's algorithmThe cheapest route from the start to every vertex is needed, not to one goal.O((V + E) log V)
A* searchA good admissible heuristic is available: g + h steers the search toward the goal and expands fewer vertices.O((V + E) log V)
Greedy best-first searchA fast route matters more than the cheapest one: rank the frontier by h only.O((V + E) log V)

Common pitfalls

  • Testing the goal too early. Stopping as soon as the goal joins the frontier returns the first route found. On the Romania map that is the 450 km route, not the 418 km one.
  • Not lowering frontier entries. When a cheaper route to a frontier vertex appears, its entry must be lowered, or a second entry added. Ignoring it, as greedy best-first does, loses optimality.
  • Negative costs. With a negative step cost a vertex can be expanded before its cheapest route is known. Uniform cost search, like Dijkstra, needs costs of 0 or more. Use Bellman-Ford otherwise.
  • Zero-cost loops. Steps that cost 0 can trap a tree search in an endless loop. An explored set, as used here, prevents it.

Frequently asked questions

What is uniform cost search?
An uninformed search algorithm that always expands the frontier node with the lowest path cost from the start. It finds the cheapest path to the goal when all step costs are 0 or more.
Is uniform cost search the same as Dijkstra's algorithm?
Essentially yes. Uniform cost search is Dijkstra's algorithm with a goal, written as graph search: it starts with only the start node on the frontier and stops when the goal is expanded, while the textbook Dijkstra computes the distances to all vertices.
Is uniform cost search optimal and complete?
It is optimal whenever step costs are 0 or more, and complete as long as every step costs at least some ε > 0 and each node has finitely many neighbours.
What is the difference between uniform cost search and BFS?
BFS expands nodes in order of the number of steps from the start, uniform cost search in order of path cost. When all steps cost the same, they find the same paths.
What is the difference between uniform cost search and A*?
A* orders the frontier by g + h, adding a heuristic estimate of the remaining cost. Uniform cost search uses g alone, so it is A* with h = 0.

Related algorithms: Dijkstra's Algorithm, A* Search Algorithm, Greedy Best-First Search, Breadth-First Search

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 20
Edges: 23