A* Search Algorithm in Artificial Intelligence
Understand how the A* Search Algorithm combines actual path cost and estimated remaining cost to find optimal solutions. Learn its evaluation function, admissible heuristics, Python implementation, complexity, advantages, limitations, and applications.
Imagine you are travelling from one city to another. You have several possible routes. Some roads are shorter, while others take you far away before bringing you closer to your destination.
You need an algorithm that does not simply choose the road that looks closest to the destination. It should also consider how much distance you have already travelled.
This is exactly the problem that A Search* is designed to solve.
A* combines the actual cost of reaching a particular point with an estimate of the remaining cost. By considering both, it can find an optimal path under suitable conditions.
It is one of the most important informed search algorithms in Artificial Intelligence.
1. What Is A* Search?
A (A-star) Search* is an informed search algorithm that finds a path from an initial state to a goal state by combining the actual cost already travelled with the estimated cost remaining.
It uses the evaluation function:
\[
f(n) = g(n) + h(n)
\]
Where:
- \(f(n)\) = estimated total cost of a solution path through node \(n\).
- \(g(n)\) = actual cost from the starting node to node \(n\).
- \(h(n)\) = estimated cost from node \(n\) to the goal.
The algorithm selects the node with the lowest \(f(n)\) value for exploration.
This is the main difference between A* and Greedy Best-First Search.
Greedy Best-First Search considers only the estimated remaining cost. A* considers both the cost already travelled and the estimated remaining cost.
2. Understanding the A* Evaluation Function
Let’s understand the three values with a simple example.
Suppose a robot is moving through a map.
It has reached node A, and:
- The actual cost from the start to A is 5.
- The estimated remaining cost from A to the goal is 7.
Therefore:
\[
g(A) = 5
\]
\[
h(A) = 7
\]
\[
f(A) = 5 + 7 = 12
\]
The estimated total cost through A is 12.
Now suppose another node B has:
\[
g(B) = 3,\quad h(B) = 6
\]
Then:
\[
f(B) = 3 + 6 = 9
\]
A* prefers B because its estimated total cost is lower.
Notice that A* does not simply choose the node with the lowest remaining estimate. It considers the journey already completed as well.
3. How Does A* Search Work?
Consider this weighted search graph:
S
/ \
1/ \4
A B
/ \ \
2/ \2 \1
C D G
Suppose S is the starting node and G is the goal.
The numbers on the edges represent the actual travel costs.
Assume the heuristic values are:
| Node | Heuristic h(n) |
|---|---|
| S | 4 |
| A | 3 |
| B | 1 |
| C | 4 |
| D | 2 |
| G | 0 |
The algorithm begins at S.
Step 1: Start at S
The starting node has:
\[
g(S)=0
\]
\[
f(S)=0+4=4
\]
Explore its neighbours A and B.
Step 2: Calculate the costs
For A:
\[
g(A)=1,\quad f(A)=1+3=4
\]
For B:
\[
g(B)=4,\quad f(B)=4+1=5
\]
A has the lower estimated total cost, so A is selected.
Step 3: Explore A
A has two neighbours: C and D.
For C:
\[
g(C)=1+2=3
\]
\[
f(C)=3+4=7
\]
For D:
\[
g(D)=1+2=3
\]
\[
f(D)=3+2=5
\]
The available nodes now include B, C, and D. D has the lowest estimated total cost among them.
Step 4: Explore D
D has no further neighbours in this example. The algorithm continues with B.
Step 5: Explore B
B connects to G.
\[
g(G)=4+1=5
\]
\[
f(G)=5+0=5
\]
The goal has been reached.
The path is:
\[
S \rightarrow B \rightarrow G
\]
The total path cost is:
\[
4+1=5
\]
A* has found the least-cost path in this example.
4. The Role of a Priority Queue
A* commonly uses a priority queue to manage the nodes waiting to be explored.
Each node is assigned a priority based on its (f(n)) value.
The node with the lowest estimated total cost is selected first.
For example:
| Node | g(n) | h(n) | f(n) |
|---|---|---|---|
| A | 3 | 5 | 8 |
| B | 4 | 2 | 6 |
| C | 2 | 7 | 9 |
Node B is selected first because its estimated total cost is 6.
This process continues until the goal is reached.
5. A* Search Algorithm
The general steps of A* are:
- Start with the initial node.
- Set its actual path cost \(g(n)\) to zero.
- Calculate its evaluation value using \(f(n)=g(n)+h(n)\).
- Insert it into the priority queue.
- Remove the node with the lowest \(f(n)\) value.
- If it is the goal, reconstruct and return the path.
- Otherwise, examine its neighbours.
- Calculate the new path cost for each neighbour.
- If a better path is found, update its cost and parent information.
- Continue until the goal is found or no nodes remain.
An important detail is that A* must update a node when it discovers a cheaper route to that node. Simply marking a node visited the first time it is encountered can produce incorrect results in some implementations.
6. Implementing A* Search in Python
Let’s implement A* using Python’s heapq module.
We will use a small weighted graph. Each edge has a cost, and each node has a heuristic estimate.
import heapq
graph = {
'S': [('A', 1), ('B', 4)],
'A': [('C', 2), ('D', 2)],
'B': [('G', 1)],
'C': [],
'D': [],
'G': []
}
heuristic = {
'S': 4,
'A': 3,
'B': 1,
'C': 4,
'D': 2,
'G': 0
}
def a_star(start, goal):
priority_queue = [(heuristic[start], 0, start)]
cost_so_far = {start: 0}
parent = {start: None}
while priority_queue:
f, g, node = heapq.heappop(priority_queue)
# Ignore outdated queue entries
if g != cost_so_far[node]:
continue
if node == goal:
path = []
current = goal
while current is not None:
path.append(current)
current = parent[current]
path.reverse()
return path, g
for neighbour, cost in graph[node]:
new_cost = g + cost
if (neighbour not in cost_so_far or
new_cost < cost_so_far[neighbour]):
cost_so_far[neighbour] = new_cost
parent[neighbour] = node
f = new_cost + heuristic[neighbour]
heapq.heappush(
priority_queue,
(f, new_cost, neighbour)
)
return None, float('inf')
path, cost = a_star('S', 'G')
print("Path:", path)
print("Total Cost:", cost)
Output:
Path: ['S', 'B', 'G']
Total Cost: 5
Understanding the code
graphstores each node and its neighbours with their edge costs.heuristicstores the estimated remaining cost to the goal.priority_queuestores nodes according to their estimated total cost.cost_so_farrecords the best known cost to reach each node.parentstores where each node was reached from, allowing the final path to be reconstructed.heapq.heappop()selects the node with the lowest priority.heapq.heappush()adds newly discovered or improved paths.
The check g != cost_so_far[node] ignores outdated entries in the priority queue when a better route has already been found.
This implementation supports non-negative edge costs and uses a consistent heuristic for the usual optimal graph-search guarantee.
7. What Makes A* Optimal?
One of the most important properties of A* is its ability to find an optimal solution.
However, this depends on the heuristic function and the conditions of the search problem.
Two important concepts are:
Admissible Heuristic
A heuristic is admissible if it never overestimates the actual minimum remaining cost to the goal.
Mathematically:
\[
h(n) \leq h^*(n)
\]
Here, \(h^*(n)\) represents the true minimum cost from node \(n\) to the goal.
For example, if the actual shortest remaining cost is 10, an admissible heuristic may estimate 7 or 9, but it should not estimate 12.
With non-negative edge costs, an admissible heuristic supports A*’s optimality in tree search.
Consistent Heuristic
A heuristic is consistent if its estimate satisfies:
\[
h(n) \leq c(n,n’) + h(n’)
\]
Here:
- \(n\) is the current node.
- \(n’\) is a neighbouring node.
- \(c(n,n’)\) is the cost of moving between them.
Consistency is a stronger condition than admissibility. It helps ensure that estimated costs behave properly as the search moves through the graph.
For graph search with a consistent heuristic, A* can safely expand nodes without needing to reopen previously expanded nodes.
8. Properties of A* Search
Let’s examine the main properties.
| Property | Description |
|---|---|
| Search type | Informed search |
| Evaluation function | \(f(n)=g(n)+h(n)\) |
| Data structure | Priority queue |
| Completeness | Yes, under standard finite-branching and positive-cost conditions |
| Optimality | Yes, with suitable heuristic conditions |
| Time complexity | Exponential in the worst case |
| Space complexity | Exponential in the worst case |
A commonly cited worst-case time and space bound for tree search is:
\[
O(b^d)
\]
Where:
- \(b\) = branching factor.
- \(d\) = depth of the optimal solution.
Actual performance depends heavily on the search space, edge costs, and quality of the heuristic.
9. Advantages of A* Search
- Finds optimal paths under suitable conditions: It can guarantee the least-cost solution when its assumptions are satisfied.
- Uses heuristic knowledge: It avoids treating every possible path as equally promising.
- Combines two types of information: It considers both the actual cost and estimated remaining cost.
- Widely applicable: It can solve route-finding, robotics, and puzzle problems.
- Flexible: Different heuristic functions can be designed for different problems.
10. Limitations of A* Search
- High memory usage: It stores many generated nodes, which can become expensive for large search spaces.
- Depends on the heuristic: A poor heuristic may cause it to explore many unnecessary nodes.
- Can be computationally expensive: Its search space may grow rapidly.
- Requires cost information: It needs meaningful path costs and a way to estimate remaining costs.
A* is powerful, but it is not always the best choice when memory or computation is severely limited.
11. Applications of A* Search
A* is used in many fields where finding a good or optimal path is important.
- GPS and navigation: Finding routes between locations.
- Robotics: Planning movement while avoiding obstacles.
- Video games: Finding paths for characters and other game objects.
- Puzzle solving: Finding solutions to problems such as the 8-puzzle.
- Network routing: Finding low-cost paths through networks.
- Autonomous systems: Planning sequences of movements or actions.
12. Greedy Best-First Search vs A*
Both algorithms use heuristic information, but their decision-making processes are different.
| Feature | Greedy Best-First Search | A* Search |
|---|---|---|
| Evaluation | \(f(n)=h(n)\) | \(f(n)=g(n)+h(n)\) |
| Cost already travelled | Ignored | Considered |
| Remaining estimated cost | Considered | Considered |
| Optimality | Not guaranteed | Guaranteed under suitable conditions |
| Main focus | Reach what looks closest | Find the lowest estimated total-cost path |
Greedy Best-First Search can sometimes find a solution faster, but A* makes a more balanced decision by considering the complete cost estimate.
Conclusion
A* Search is one of the most important algorithms in informed search because it combines the actual cost of reaching a node with an estimate of the remaining cost.
This allows it to make more balanced decisions than Greedy Best-First Search and, under suitable conditions, find an optimal path.
Its applications range from navigation systems and robotics to games and intelligent planning.
In the next article, we will take a closer look at the component that makes informed search possible: Heuristic Functions.
Quick quiz
5 questionsOriginally published at farhanpaal.com — https://farhanpaal.com/articles/a-star-search-algorithm-in-artificial-intelligence/
Keep a copy
Read offline as a printout or PDF.
farhanpaal.com