A Search Algorithm
A Search Algorithm
DSA Tutorial Interview Questions Quizzes Must Do Advanced DSA System Design Aptitude Puzzles Interview Corner DSA Python
Data Structures
Motivation
Algorithms To approximate the shortest path in real-life situations, like- in maps, games where there can be many
We can consider a 2D Grid having several obstacles and we start from a source cell (colored red below
Advanced goal cell (colored green below)
Interview Preparation
Practice Problem
Explanation
Consider a square grid having many obstacles and we are given a starting cell and a target cell. We w
target cell (if possible) from the starting cell as quickly as possible. Here A* Search Algorithm comes t
What A* Search Algorithm does is that at each step it picks the node according to a value-‘f’ which is
the sum of two other parameters - ‘g’ and ‘h’. At each step it picks the node/cell having the lowest ‘f’, a
node/cell.
We define ‘g’ and ‘h’ as simply as possible below
g = the movement cost to move from the starting point to a given square on the grid, following the pa
there.
h = the estimated movement cost to move from that given square on the grid to the final destination. T
to as the heuristic, which is nothing but a kind of smart guess. We really don’t know the actual distanc
path, because all sorts of things can be in the way (walls, water, etc.). There can be many ways to calc
are discussed in the later sections.
Algorithm
We create two lists – Open List and Closed List (just like Dijkstra Algorithm)
// A* Search Algorithm
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 1 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
So suppose as in the below figure if we want to reach the target cell from the source cell, then the A*
would follow path as shown below. Note that the below figure is made by considering Euclidean Dista
Heuristics
We can calculate g but how to calculate h ?
We can do things.
A) Either calculate the exact value of h (which is certainly time consuming).
OR
B ) Approximate the value of h using some heuristics (less time consuming).
We will discuss both of the methods.
A) Exact Heuristics -
We can find exact values of h, but that is generally very time consuming.
Below are some of the methods to calculate the exact value of h.
1) Pre-compute the distance between each pair of cells before running the A* Search Algorithm.
2) If there are no blocked cells/obstacles then we can just find the exact value of h without any pre-co
distance formula/Euclidean Distance
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 2 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
B) Approximation Heuristics -
There are generally three approximation heuristics to calculate h -
1) Manhattan Distance -
It is nothing but the sum of absolute values of differences in the goal’s x and y coordinates and the
coordinates respectively, i.e.,
When to use this heuristic? – When we are allowed to move only in four directions only (right, left,
The Manhattan Distance Heuristics is shown by the below figure (assume red spot as source cell and
cell).
2) Diagonal Distance-
It is nothing but the maximum of absolute values of differences in the goal’s x and y coordinates an
and y coordinates respectively, i.e.,
dx = abs(current_cell.x – goal.x)
dy = abs(current_cell.y – goal.y)
When to use this heuristic? – When we are allowed to move in eight directions only (similar to a mo
Chess)
The Diagonal Distance Heuristics is shown by the below figure (assume red spot as source cell and gr
cell).
3) Euclidean Distance-
As it is clear from its name, it is nothing but the distance between the current cell and the goal cell
formula
When to use this heuristic? – When we are allowed to move in any directions.
The Euclidean Distance Heuristics is shown by the below figure (assume red spot as source cell and g
cell).
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 3 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
Implementation
We can use any data structure to implement open list and closed list but for best performance, we use
of C++ STL(implemented as Red-Black Tree) and a boolean hash table for a closed list.
The implementations are similar to Dijkstra's algorithm. If we use a Fibonacci heap to implement the o
binary heap/self-balancing tree, then the performance will become better (as Fibonacci heap takes O(1
insert into open list and to decrease key)
Also to reduce the time taken to calculate g, we will use dynamic programming.
#define ROW 9
#define COL 10
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 4 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
return (false);
}
stack<Pair> Path;
Path.push(make_pair(row, col));
while (!Path.empty()) {
pair<int, int> p = Path.top();
Path.pop();
printf("-> (%d,%d) ", p.first, p.second);
}
return;
}
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 5 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
return;
}
int i, j;
/*
Create an open list having information as-
<f, <i, j>>
where f = g + h,
and i, j are the row and column index of that cell
Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1
This open list is implemented as a set of pair of
pair.*/
set<pPair> openList;
// Put the starting cell on the open list and set its
// 'f' as 0
openList.insert(make_pair(0.0, make_pair(i, j)));
while (!openList.empty()) {
pPair p = *openList.begin();
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 6 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
/*
Generating all the 8 successor of this cell
N.W N N.E
\ | /
\ | /
W----Cell----E
/ | \
/ | \
S.W S S.E
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 7 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 8 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 9 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 10 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 11 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 12 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
// current successor
if (isDestination(i + 1, j - 1, dest) == true) {
// Set the Parent of the destination cell
cellDetails[i + 1][j - 1].parent_i = i;
cellDetails[i + 1][j - 1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
return;
}
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 13 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
= { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } };
return (0);
}
Limitations
Although being the best path finding algorithm around, A* Search Algorithm doesn’t produce the shor
it relies heavily on heuristics / approximations to calculate - h
Applications
This is the most interesting part of A* Search Algorithm. They are used in games! But how?
Ever played Tower Defense Games ?
Tower defense is a type of strategy video game where the goal is to defend a player's territories or po
obstructing enemy attackers, usually achieved by placing defensive structures on or along their path o
A* Search Algorithm is often used to find the shortest path from one point to another point. You can us
enemy to find a path to the goal.
One example of this is the very popular game- Warcraft III
Time Complexity
Considering a graph, it may take us to travel all the edge to reach the destination cell from the source
consider a graph where source and destination nodes are connected by a series of edges, like - 0(sour
(target)
So the worse case time complexity is O(E), where E is the number of edges in the graph
Auxiliary Space In the worse case we can have all the edges inside the open list, so required auxiliary
is O(V), where V is the total number of vertices.
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 14 of 15
A* Search Algorithm - GeeksforGeeks 05/11/25, 1:32 PM
Summary
So when to use BFS over A*, when to use Dijkstra over A* to find the shortest paths ?
We can summarise this as below-
1) One source and One Destination-
? Use A* Search Algorithm (For Unweighted as well as Weighted Graphs)
2) One Source, All Destination -
? Use BFS (For Unweighted Graphs)
? Use Dijkstra (For Weighted Graphs without negative weights)
? Use Bellman Ford (For Weighted Graphs with negative weights)
3) Between every pair of nodes-
? Floyd-Warshall
? Johnson’s Algorithm
Related Article:
Best First Search (Informed Search)
References-
http://theory.stanford.edu/~amitp/GameProgramming/
https://en.wikipedia.org/wiki/A*_search_algorithm
Comment K kartik
https://www.geeksforgeeks.org/dsa/a-search-algorithm/ Page 15 of 15