A* Algorithm
In the world of computer science, algorithms are the unsung heroes that power much of the technology we use daily. Among them, the A* (A-star) algorithm stands out as a powerful and efficient tool for pathfinding and graph traversal. Whether you’re navigating a map in your GPS or coding AI for a video game, A* is a go-to algorithm. In this blog, we’ll explore what makes A* so special, how it works, and where it’s applied.
What is the A* Algorithm?
The A* algorithm is a popular search algorithm used to find the shortest path between two points. It combines the strengths of Dijkstra’s algorithm (which guarantees the shortest path) and Greedy Best-First Search (which uses heuristics to guide the search). By balancing these two approaches, A* achieves both efficiency and accuracy.
How Does A* Work?
At its core, A* uses a priority queue to explore nodes on a graph. It evaluates each node using the formula
- f(n) - Total estimated cost of the cheapest path through node.
- g(n) - Cost of the path from the starting point to node.
- h(n) - Estimated cost (heuristic) from node to the goal.
The algorithm prioritizes nodes with the lowest, ensuring a balance between the shortest known path and the estimated distance to the goal.
Steps of the A* Algorithm
Initialization
- Start with an open list (nodes to be evaluated) and a closed list (nodes already evaluated).
- Add the starting node to the open list.
Node Evaluation
- While the open list is not empty, choose the node with the lowest .
- If this node is the goal, reconstruct and return the path.
Expand Neighbors
- For each neighbor of the current node, calculate , , and .
- If the neighbor isn’t in the open list or has a better , update its values and add it to the open list.
Repeat
- Move the current node to the closed list and repeat until the goal is reached or the open list is empty.
Heuristics in A*
The choice of heuristic greatly affects the algorithm’s performance. A good heuristic is
- Admissible - Never overestimates the actual cost to reach the goal.
- Consistent - For any two nodes and , the estimated cost from to should not exceed the direct cost between them plus the heuristic from to the goal.
Common heuristics include
- Manhattan Distance - For grid-based maps.
- Euclidean Distance -For continuous spaces.
- Chebyshev Distance -When diagonal movements are allowed.
Example Use Case - Maze Navigation
Imagine you are tasked with programming a robot to navigate a maze and reach the goal. The robot starts at a predefined point, and the maze contains walls, open spaces, and a goal node.
Get UvinduHerath’s stories in your inbox
Join Medium for free to get updates from this writer.
Using the A* algorithm
- g(n) represents the distance the robot has traveled from the start node.
- h(n) is calculated using the Manhattan distance to the goal.
- f(n) combines the actual distance and the heuristic to guide the robot efficiently.
Below is a diagram illustrating how A* explores the maze
S = Start, G = Goal, X = Wall, O = Open Node
Before Exploration
S O O X X
X O X X G
O O O O XExploration Process
1. Explore nodes closest to S with the lowest f(n).
2. Gradually expand outward toward G, avoiding walls.
3. Final path is reconstructed once G is reached.
Coding Example
Here is a Python implementation of the A* algorithm
import heapq
def a_star_algorithm(start, goal, graph, h):
open_list = []
closed_list = set()
g_cost = {start: 0}
heapq.heappush(open_list, (h[start], start))
came_from = {}
while open_list:
_, current = heapq.heappop(open_list)
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
closed_list.add(current)
for neighbor, cost in graph[current]:
if neighbor in closed_list:
continue
tentative_g_cost = g_cost[current] + cost
if neighbor not in g_cost or tentative_g_cost < g_cost[neighbor]:
came_from[neighbor] = current
g_cost[neighbor] = tentative_g_cost
f_cost = tentative_g_cost + h[neighbor]
heapq.heappush(open_list, (f_cost, neighbor))
return None
# Define the graph and heuristic
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 1), ('E', 4)],
'C': [('E', 2)],
'D': [('G', 4)],
'E': [('G', 1)],
'G': []
}
heuristic = {
'A': 6,
'B': 4,
'C': 4,
'D': 2,
'E': 2,
'G': 0
}
start = 'A'
goal = 'G'
path = a_star_algorithm(start, goal, graph, heuristic)
print("Shortest Path:", path)Advantages of A*
- Guaranteed Optimality -Finds the shortest path if the heuristic is admissible.
- Efficiency - Focuses on the most promising paths, reducing unnecessary computations.
- Flexibility - Adapts well to various problem spaces with appropriate heuristics.
Limitations of A*
- High Memory Usage - Stores all evaluated nodes, which can be problematic for large graphs.
- Performance Dependent on Heuristic - Poor heuristic choices can make the algorithm inefficient.
Applications of A*
- Game Development
- AI characters use A* for pathfinding, navigating complex environments efficiently.
2. Robotics
- Robots use A* to plan movements in real-world spaces while avoiding obstacles.
3. Navigation Systems
- GPS applications use A* to calculate optimal routes.
4. Logistics and Planning
- Warehouse robots and delivery drones rely on A* to optimize routes.
If you enjoyed this post, please click the clap button and share your thoughts. Thank you for reading! 👏










