Uniform Cost Search (UCS)
Learn Uniform Cost Search (UCS) in Artificial Intelligence. Understand how it uses a priority queue to find the least-cost path, with a worked example, Python implementation, dry run, complexity analysis, and practical applications.
Imagine you are travelling from one city to another. You have several possible routes, but each route has a different distance, travel time, or cost.
Would you always choose the route with the fewest roads?
Not necessarily.
A route with fewer roads might be more expensive, while another route with more connections could be cheaper. What matters is not simply how many steps you take, but the total cost of reaching your destination.
This is a problem that Artificial Intelligence systems often need to solve.
In the previous article, we studied Breadth-First Search (BFS), which explores nodes level by level. But BFS does not consider different path costs when deciding which node to explore next.
So, what happens when every action has a different cost?
This is where Uniform Cost Search (UCS) becomes useful.
UCS is an uninformed search algorithm that explores the path with the lowest accumulated cost first. Let’s understand how it works, why it uses a priority queue, and how we can implement it using Python.
What Is Uniform Cost Search?
Uniform Cost Search (UCS) is an uninformed search algorithm that always expands the node with the lowest total path cost from the starting point.
In simple words, it chooses the cheapest path explored so far.
Unlike BFS, which explores nodes according to their depth, UCS considers the total cost of reaching each node.
For example, imagine travelling from city A to city G. There are several possible routes, and each road has a different travel cost.
UCS examines the available routes and prioritises the one with the lowest accumulated cost.
It continues this process until it reaches the goal.
The important point is that UCS does not simply select the next nearby node. It selects the node that can currently be reached at the lowest total cost.
1. Understanding Path Cost
Before understanding the algorithm, we need to understand what path cost means.
Path cost is the total cost accumulated while moving from the initial state to a particular state.
Suppose we have three possible routes:
- Route A: Cost = 2 + 3 = 5
- Route B: Cost = 4 + 2 = 6
- Route C: Cost = 1 + 7 = 8
Although these routes contain different numbers of steps, their total costs are what matter.
UCS compares these accumulated costs and explores the cheapest available path first.
We can represent the cost of a path using:
\[
g(n) = \text{Total cost from the start node to node } n
\]
Here, \(g(n)\) represents the accumulated path cost of reaching node \(n\).
Every time the algorithm moves to a new node, it adds the cost of that action to the existing path cost.
2. Why Does UCS Use a Priority Queue?
This is one of the most important concepts in Uniform Cost Search.
A normal queue follows the First In, First Out (FIFO) principle. The element added first is removed first.
But UCS cannot simply follow the order in which nodes are added. It must select the node with the lowest accumulated cost.
For this reason, UCS uses a priority queue.
A priority queue is a data structure in which elements are removed according to their priority rather than simply their insertion order.
In UCS, the priority is the total path cost.
For example, imagine the priority queue contains:
| Node | Path cost |
|---|---|
| A | 5 |
| B | 2 |
| C | 8 |
| D | 4 |
Which node should UCS explore next?
It selects B because its path cost is 2, the lowest among the available options.
After exploring B, the algorithm updates the queue with any newly discovered or improved paths.
This process continues until the goal is reached.
3. How Does Uniform Cost Search Work?
Let’s understand UCS using a simple search graph.
Imagine the following connections:
2
A ---------- B
| |
1 | 5 |
| |
C ---------- D
2
Start: A
Goal: D
There are two main routes from A to D:
- A → B → D = 2 + 5 = 7
- A → C → D = 1 + 2 = 3
The cheapest route is A → C → D, with a total cost of 3.
Let’s see how UCS discovers it.
Step 1: Start at A
The initial node is A, so its path cost is 0.
Priority queue: [(A, 0)]
Step 2: Explore A
A has two neighbours:
- B with cost 2
- C with cost 1
Add both to the priority queue.
[(C, 1), (B, 2)]
C comes first because its cost is lower.
Step 3: Explore C
We remove C and examine its neighbours.
D can be reached from C with an additional cost of 2.
The total cost of reaching D through C is:
\[
1 + 2 = 3
\]
The updated priority queue is: [(B, 2), (D, 3)]
Step 4: Explore B
B has a path to D with an additional cost of 5.
The total cost through B would be:
\[
2 + 5 = 7
\]
However, we have already discovered a cheaper route to D with a cost of 3.
Therefore, the algorithm keeps the cheaper route.
Step 5: Reach the Goal
D is now the lowest-cost node in the priority queue.
UCS removes D and checks whether it is the goal. Since it is, the algorithm stops.
The final path is:
A → C → D
Total path cost = 3
This example shows the main principle of UCS: always expand the available path with the lowest accumulated cost.
4. UCS Algorithm
Now let’s express the working of UCS in a general algorithm.
Input: A weighted graph, starting node, and goal node.
Output: The least-cost path to the goal, if one exists.
The basic steps are:
- Create a priority queue.
- Insert the starting node with a path cost of 0.
- Maintain the lowest known cost for each discovered node.
- While the priority queue is not empty:
- Remove the node with the lowest path cost.
- If its cost is outdated, skip it.
- If the node is the goal, return its path.
- Examine its neighbouring nodes.
- Calculate the new path cost for each neighbour.
- If a cheaper path is found, update its cost and add it to the priority queue.
- If the queue becomes empty without finding the goal, return failure.
Notice that UCS may discover a node through multiple paths. It must therefore keep track of the cheapest known cost and update it whenever a better route is found.
5. Implementing UCS Using Python
Let’s implement Uniform Cost Search using Python.
We will represent the graph using an adjacency list. Each connection contains a neighbouring node and the cost of travelling to it.
import heapq
graph = {
'A': [('B', 2), ('C', 1)],
'B': [('A', 2), ('D', 5)],
'C': [('A', 1), ('D', 2)],
'D': [('B', 5), ('C', 2)]
}
def uniform_cost_search(graph, start, goal):
priority_queue = [(0, start)]
costs = {start: 0}
parent = {start: None}
while priority_queue:
cost, node = heapq.heappop(priority_queue)
if cost > costs[node]:
continue
if node == goal:
path = []
current = goal
while current is not None:
path.append(current)
current = parent[current]
return path[::-1], cost
for neighbour, edge_cost in graph[node]:
new_cost = cost + edge_cost
if new_cost < costs.get(neighbour, float('inf')):
costs[neighbour] = new_cost
parent[neighbour] = node
heapq.heappush(
priority_queue,
(new_cost, neighbour)
)
return None, float('inf')
path, cost = uniform_cost_search(graph, 'A', 'D')
print("Path:", path)
print("Total Cost:", cost)
Output:
Path: ['A', 'C', 'D']
Total Cost: 3
Let’s understand the important parts.
1. Importing heapq
import heapq
Python’s heapq module provides a heap-based priority queue. It allows us to efficiently retrieve the element with the smallest priority.
2. Creating the priority queue
priority_queue = [(0, start)]
The starting node is inserted with a cost of 0.
Each entry contains two values: the accumulated path cost and the node.
3. Tracking costs
costs = {start: 0}
This dictionary stores the lowest known cost for reaching each node.
4. Removing the cheapest node
cost, node = heapq.heappop(priority_queue)
This removes the entry with the lowest cost from the priority queue.
5. Updating a path
new_cost = cost + edge_cost
The algorithm adds the cost of the next connection to the existing path cost.
If the new path is cheaper than the previously known path, it updates the cost and inserts the improved option into the priority queue.
6. Reconstructing the path
The parent dictionary remembers which node led to each improved path. Once the goal is reached, we follow these parent references backwards to reconstruct the complete route.
The algorithm also checks whether a removed entry has an outdated cost. This is important because the same node may enter the priority queue more than once after a better route is discovered.
6. Dry Run of UCS
A dry run means tracing an algorithm manually to understand how its variables and data structures change.
Let’s perform a dry run using the same graph.
Starting node: A
Goal node: D
| Step | Node explored | New information | Priority queue |
|---|---|---|---|
| 1 | A | B = 2, C = 1 | C(1), B(2) |
| 2 | C | D = 3 | B(2), D(3) |
| 3 | B | D through B = 7, not better | D(3) |
| 4 | D | Goal reached | Empty |
The algorithm returns:
A → C → D
Total cost:
\[
1 + 2 = 3
\]
The important observation is that UCS does not stop when it first discovers the goal. It stops when the goal is removed from the priority queue as the lowest-cost available node.
This distinction is essential to understanding why UCS can guarantee an optimal solution under suitable conditions.
7. Completeness and Optimality of UCS
Uniform Cost Search has two important properties.
Completeness
UCS is complete when every action has a cost greater than some positive minimum value and the branching factor is finite.
This means it will find a solution if one exists under these conditions.
Optimality
UCS is optimal when all action costs are non-negative.
It finds the goal through the path with the lowest total cost, provided the algorithm is implemented correctly.
This makes UCS especially useful when different actions have different costs.
8. Time and Space Complexity of UCS
The complexity of UCS depends on the structure of the search space and the costs of its actions.
Unlike BFS, its performance is not described simply by the depth of the goal. It also depends on how many paths have a cost lower than the optimal solution.
Let:
- \(C^*\) = Cost of the optimal solution.
- \(\epsilon\) = Minimum positive cost of an action.
- \(b\) = Branching factor.
In the worst case, UCS may explore a very large number of nodes before reaching the goal.
A commonly used upper-bound expression is:
\[
O\left(b^{1+\lfloor C^*/\epsilon \rfloor}\right)
\]
The space complexity has the same exponential character because UCS may need to store many generated nodes in its priority queue.
This explains why UCS can become expensive when the search space is large or when action costs are very small.
9. UCS vs BFS
Both BFS and UCS are uninformed search algorithms, but they select nodes differently.
| Feature | BFS | UCS |
|---|---|---|
| Selection rule | Shallowest node first | Lowest path cost first |
| Data structure | Queue | Priority queue |
| Considers path cost | No | Yes |
| Complete | Under finite branching | Under suitable positive-cost conditions |
| Optimality | When all step costs are equal | With non-negative costs and suitable conditions |
| Best suited for | Unweighted graphs | Weighted graphs |
An important point: when all actions have the same cost, UCS and BFS can find the same least-cost solution. However, when costs differ, UCS is generally the more appropriate choice.
10. Advantages and Limitations of UCS
Advantages
- It finds the least-cost solution under suitable conditions.
- It handles problems where actions have different costs.
- It does not require heuristic information.
- It is useful for weighted graphs and cost-based planning problems.
Limitations
- It can require significant memory.
- It may explore many nodes before reaching the goal.
- It can be slower than simpler search algorithms for some problems.
- Its performance depends on the costs and structure of the search space.
11. Real-World Applications of UCS
Uniform Cost Search is useful wherever the goal is to find a solution with the lowest accumulated cost.
1. Route Planning
A navigation system can use cost-based search to identify a route with the lowest travel cost. The cost might represent distance, time, or fuel consumption.
2. Network Routing
Computer networks can use path costs to select routes through connected devices. The cost may represent delay, bandwidth usage, or another network metric.
3. Resource Planning
An AI system can explore different ways of completing a task while considering the resources required for each action.
4. Robotics
A robot can search for a path while considering movement costs, such as energy consumption or movement distance.
5. Game and Puzzle Solving
When different actions have different costs, UCS can find a solution that minimises the total cost rather than simply the number of moves.
Conclusion
Uniform Cost Search is an important uninformed search algorithm because it considers the total cost of reaching a state rather than simply the number of steps taken.
We have seen how it uses a priority queue, how it selects the lowest-cost path, and how to implement it using Python.
Its most important strength is its ability to find an optimal solution when action costs are non-negative and the required search conditions are satisfied.
However, UCS can consume significant time and memory when the search space becomes large.
This raises another interesting question: what if we want an algorithm to explore deeply along one path before considering other possibilities?
In the next article, we will study Depth-First Search (DFS) and understand how it explores a search space by following one path as far as possible before backtracking.
Quick quiz
5 questionsOriginally published at farhanpaal.com — https://farhanpaal.com/articles/uniform-cost-search-ucs/
Keep a copy
Read offline as a printout or PDF.
farhanpaal.com