0% found this document useful (0 votes)
38 views9 pages

Lab 10

Uploaded by

Isra Asif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views9 pages

Lab 10

Uploaded by

Isra Asif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

FATIMA JINNAH WOMEN UNIVERSITY

Department of Computer Science


LAB MANUAL: Artificial Intelligence

Note:
In preparation of these materials have been taken from different online

sources in the shape of books, websites, research papers and presentations etc.

However, the author does not have any intention to take any benefit of these in her/his

own name. This lecture (audio, video, slides etc.) is prepared and delivered only for

educational purposes and is not intended to infringe upon the copyrighted material.

Sources have been acknowledged where applicable. The views expressed are

presenter’s alone and do not necessarily represent actual author(s) or the institution.

Lab 10
A* Algorithm
Motivation

To approximate the shortest path in real-life situations, like- in maps, games where there can be
many hindrances.
We can consider a 2D Grid having several obstacles and we start from a source cell (coloured
red below) to reach towards a goal cell (coloured green below)

What is A* Search Algorithm?


A* Search algorithm is one of the best and popular technique used in path-finding and graph
traversals.
Why A* Search Algorithm ?
Informally speaking, A* Search algorithms, unlike other traversal techniques, it has “brains”.
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

What it means is that it is really a smart algorithm which separates it from the other conventional
algorithms. This fact is cleared in detail in below sections.
And it is also worth mentioning that many games and web-based maps use this algorithm to find
the shortest path very efficiently (approximation).

Explanation
Consider a square grid having many obstacles and we are given a starting cell and a target cell.
We want to reach the target cell (if possible) from the starting cell as quickly as possible. Here
A* Search Algorithm comes to the rescue.
What A* Search Algorithm does is that at each step it picks the node according to a value-‘f’
which is a parameter equal to the sum of two other parameters – ‘g’ and ‘h’. At each step it picks
the node/cell having the lowest ‘f’, and process that 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 path generated to get there.
h = the estimated movement cost to move from that given square on the grid to the final
destination. This is often referred to as the heuristic, which is nothing but a kind of smart guess.
We really don’t know the actual distance until we find the path, because all sorts of things can be
in the way (walls, water, etc.). There can be many ways to calculate this ‘h’ which are discussed
in the later sections.
Algorithm
We create two lists – Open List and Closed List (just like Dijkstra Algorithm)
// A* Search Algorithm
1. Initialize the open list
2. Initialize the closed list
put the starting node on the open
list (you can leave its f at zero)

3. while the open list is not empty


a) find the node with the least f on
the open list, call it "q"

b) pop q off the open list

c) generate q's 8 successors and set their


parents to q

d) for each successor


i) if successor is the goal, stop search
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

successor.g = q.g + distance between


successor and q
successor.h = distance from goal to
successor (This can be done using many
ways, we will discuss three heuristics-
Manhattan, Diagonal and Euclidean
Heuristics)

successor.f = successor.g + successor.h

ii) if a node with the same position as


successor is in the OPEN list which has a
lower f than successor, skip this successor

iii) if a node with the same position as


successor is in the CLOSED list which has
a lower f than successor, skip this successor
otherwise, add the node to the open list
end (for loop)

e) push q on the closed list


end (while loop)
So suppose as in the below figure if we want to reach the target cell from the source cell, then the
A* Search algorithm would follow path as shown below. Note that the below figure is made by
considering Euclidean Distance as a heuristics.

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).
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

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-computation using the distance formula/Euclidean Distance
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 current cell’s x and y coordinates respectively, i.e.,
 h = abs (current_cell.x – goal.x) +
abs (current_cell.y – goal.y)
 When to use this heuristic? – When we are allowed to move only in four directions only
(right, left, top, bottom)
The Manhattan Distance Heuristics is shown by the below figure (assume red spot as source cell
and green spot as target cell).

2) Diagonal Distance-
 It is nothing but the maximum of absolute values of differences in the goal’s x and y
coordinates and the current cell’s x and y coordinates respectively, i.e.,
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

 h = max { abs(current_cell.x – goal.x),


abs(current_cell.y – goal.y) }
 When to use this heuristic? – When we are allowed to move in eight directions only
(similar to a move of a King in Chess)
The Diagonal Distance Heuristics is shown by the below figure (assume red spot as source cell
and green spot as target 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 using the distance formula
 h = sqrt ( (current_cell.x – goal.x)2 +
(current_cell.y – goal.y)2 )
 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 green spot as target cell).
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

Relation (Similarity and Differences) with other algorithms-


Dijkstra is a special case of A* Search Algorithm, where h = 0 for all nodes.
Implementation
We can use any data structure to implement open list and closed list but for best performance we
use a set data structure of C++ STL(implemented as Red-Black Tree) and a boolean hash table
for a closed list.
The implementations are similar to Dijsktra’s algorithm. If we use a Fibonacci heap to
implement the open list instead of a binary heap/self-balancing tree, then the performance will
become better (as Fibonacci heap takes O(1) average time to insert into open list and to decrease
key)
Also to reduce the time taken to calculate g, we will use dynamic programming.

Tasks
 Understand the problem
 Implement any game that implements a* algorithm using java, c#, CLISP or python
 Use any IDE
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

A* Algorithm Implementation in Python

import math
import heapq

class Node:
def __init__(self, x, y, g=0, h=0, parent=None):
self.x = x
self.y = y
self.g = g # Cost from start to current node
self.h = h # Heuristic cost from current node to goal
self.f = g + h # Total cost
self.parent = parent # To trace back the path

def __lt__(self, other):


return self.f < other.f

def manhattan_distance(node, goal):


return abs(node.x - goal.x) + abs(node.y - goal.y)

def a_star_algorithm(grid, start, goal):


open_list = []
closed_list = set()
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

start_node = Node(*start, h=manhattan_distance(Node(*start), Node(*goal)))


goal_node = Node(*goal)
heapq.heappush(open_list, start_node)

while open_list:
current_node = heapq.heappop(open_list)

if (current_node.x, current_node.y) in closed_list:


continue

closed_list.add((current_node.x, current_node.y))

if (current_node.x, current_node.y) == (goal_node.x, goal_node.y):


path = []
while current_node:
path.append((current_node.x, current_node.y))
current_node = current_node.parent
return path[::-1] # Return reversed path

for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # Movement: up, down, left, right
x, y = current_node.x + dx, current_node.y + dy
if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == 0: # Check boundaries
and obstacles
successor = Node(x, y, g=current_node.g + 1,
h=manhattan_distance(Node(x, y), goal_node),
parent=current_node)
FATIMA JINNAH WOMEN UNIVERSITY
Department of Computer Science
LAB MANUAL: Artificial Intelligence

if (x, y) not in closed_list:


heapq.heappush(open_list, successor)

return None # No path found

# Example Usage
if __name__ == "__main__":
grid = [
[0, 0, 0, 0, 1],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 0, 0, 0, 0]
]
start = (0, 0) # Starting position
goal = (4, 4) # Goal position

path = a_star_algorithm(grid, start, goal)


if path:
print("Path found:", path)
else:
print("No path found.")

You might also like