Professional Documents
Culture Documents
LAB
Experiment No: 7
Aim: To implement 8 –puzzle problem using A* search technique.
Theory:
A* uses a best-first search and finds the least-cost path from a given initial node to one goal node
(out of one or more possible goals).
It uses a distance-plus-cost heuristic function (usually denoted f(x)) to determine the order in which
the search visits nodes in the tree. The distance-plus-cost heuristic is a sum of two functions:
The path-cost function, which is the cost from the starting node to the current node (usually
denoted g(x)) and an admissible "heuristic estimate" of the distance to the goal (usually denoted
h(x)).
The h(x) part of the f(x) function must be an admissible heuristic; that is, it must not overestimate
the distance to the goal. Thus, for an application like routing, h(x) might represent the straight- line
distance to the goal, since that is physically the smallest possible distance between any two points
or nodes.
Algorithm:
Pseudo code:
function A*(start,goal)
closedset := the empty set // The set of nodes already evaluated.
openset := {start} // The set of tentative nodes to be evaluated, initially containing the start
node
came_from := the empty map // The map of navigated nodes.
1
60003180058 AI VARUN VORA
LAB
if y not in openset
add y to openset
tentative_is_better := true
else if tentative_g_score < g_score[y]
tentative_is_better := true
else
tentative_is_better := false
if tentative_is_better = true
came_from[y] := x
g_score[y] := tentative_g_score
h_score[y] := heuristic_cost_estimate(y, goal)
f_score[y] := g_score[y] + h_score[y]
return failure
Problem Definition:
Code:
import numpy as np
2
60003180058 AI VARUN VORA
LAB
start_state = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
class State:
self.data = data
self.level = level
self.fval = fval
temp = []
for i in root:
t = []
for j in i:
t.append(j)
temp.append(t)
return temp
def generate_child(self):
x, y = self.find(self.data, 0)
children = []
for i in val_list:
3
60003180058 AI VARUN VORA
LAB
if child is not None:
children.append(child_node)
return children
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None
if puz[i][j] == x:
return i, j
class A_Star:
4
60003180058 AI VARUN VORA
LAB
self.open = []
self.closed = []
state_1 = np.asmatrix(mat_1)
state_2 = np.asmatrix(mat_2)
curr_level = 0
start = State(start_state, 0, 0)
curr_level += 1
self.open.append(start)
print("\n\n")
while True:
cur = self.open[0]
print("")
print(" | ")
print(" | ")
print("\n")
for i in cur.data:
for j in i:
5
60003180058 AI VARUN VORA
LAB
print("")
break
for i in cur.generate_child():
curr_level += 1
self.open.append(i)
self.closed.append(cur)
del self.open[0]
obj = A_Star()
obj.find_goal(start_state, goal_state)
Output: