Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

A * Search

ALGO
1. Declare op = [], cl = [], nos = {}, graph = {}
2. Read no of nodes of graph ‘n’
3. Read n nodes and their childs.
3.1. Store number of childs of ith node into ith position of nos (i.e. nos[i]= no of child
nodes)
3.2. Store childs of ith node into ith position of graph (i.e. graph[i]= [child1, child2, ...
])
4. Create empty array g = [[0]*c]*r for storing path costs.
5. Declare h = {}
6. Read h(n) values for each node into h{}
7. Read path costs between nodes i and its childs ( childs = graph[i][0 to nos[i]])
7.1. Set g[i][child] = path cost
8. Read goal state
9. def astar(i):
9.1. declare f={} for storing path cost + h(n) values
9.2. declare ff={} for matching f values with corresponding childs
9.3. for m in range 0 to nos[i], loop
9.3.1. set f[i]= g[i][graph[i][m]] + h[i]
9.3.2. set ff[f[i]]=graph[i][m]
9.4. if f!={}
9.4.1. sort ff
9.4.2. set z = first element in sorted ff
9.4.3. print z
9.4.4. empty f and ff
9.5. else:
9.5.1. print Not complete!!
9.6. if z==goal
9.6.1. print Goal reached!!
9.7. else:
9.7.1. astar(z)
10. print(1)
11. astar(1)

PROGRAM
op = []
cl = []
nos = {}

graph = {}
n = int(input("Enter no of nodes of graph: "))
for i in range(0,n):
adj=[]
node = int(input("Enter node: "))
no = int(input("Enter no of child nodes: "))
nos[node]=no
for i in range(0,no):
val = int(input("Enter child: "))
adj.append(val)
graph[node]=adj
print(graph)

r, c = (n, 10)
g = [[0]*c]*r
print(g)
h = {}

print("Enter h(n) values for each node : ")


for i in range(1,n+1):
k=int(input())
h[i]=k
print("h(n) : ")
print(h)

pc = []

print("Enter path cost between : ")


for i in range(1,n+1):
for m in range(0,nos[i]):
print(i," and ", graph[i][m])
k=int(input())
v= graph[i][m]
g[i][v]=k

goal=int(input("Enter goal: "))

def astar(i):
f={}
ff={}
for m in range(0,nos[i]):
f[i]= g[i][graph[i][m]] + h[i]
ff[f[i]]=graph[i][m]
if (f!={}):
sortedff=sorted(ff)
z= ff[sortedff[0]]
print(z)
f={}
ff={}
else:
print("Not complete!!")
if (z==goal):
print("Goal reached!!")
else:
astar(z)
print(1)
astar(1)

OUTPUT
Enter no of nodes of graph: 5
Enter node: 1
Enter no of child nodes: 2
Enter child: 2
Enter child: 3
Enter node: 2
Enter no of child nodes: 2
Enter child: 4
Enter child: 5
Enter node: 3
Enter no of child nodes: 0
Enter node: 4
Enter no of child nodes: 0
Enter node: 5
Enter no of child nodes: 0
{1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0,
0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0,
0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Enter h(n) values for each node :
5
6
4
15
5
h(n) :
{1: 5, 2: 6, 3: 4, 4: 15, 5: 5}
Enter path cost between :
1 and 2
1
1 and 3
2
2 and 4
7
2 and 5
5
Enter goal: 5
1
2
5
Goal reached!!

You might also like