8 Puzzel Problem Using Best First Search: Import As Def
8 Puzzel Problem Using Best First Search: Import As Def
Search
In [48]: 1 import numpy as np
2
3 def D(state):
4 index = np.where(state == 0)
5 r = index[0]
6 c = index[1]
7 if(r<(state.shape[0]-1)):
8 state[r,c] = state[r+1,c]
9 state[r+1,c] = 0
10 return state
11
12 def R(state):
13 index = np.where(state == 0)
14 r = index[0]
15 c = index[1]
16 if(c<(state.shape[0]-1)):
17 state[r,c] = state[r,c+1]
18 state[r,c+1] = 0
19 return state
20
21 def U(state):
22 index = np.where(state == 0)
23 r = index[0]
24 c = index[1]
25 if(r>0):
26 state[r,c] = state[r-1,c]
27 state[r-1,c] = 0
28 return state
29
30 def L(state):
31 index = np.where(state == 0)
32 r = index[0]
33 c = index[1]
34 if(c>0):
35 state[r,c] = state[r,c-1]
36 state[r,c-1] = 0
37 return state
In [67]: 1 def rearrange(que, hval):
2
3 sortedH = sorted(hval)
4 newQ = np.copy(que)
5 for i in range(len(hval)):
6 newQ[i] = que[hval.index(sortedH[i])]
7
8 """ for q,h in zip(newQ, sortedH):
9 print(q,"= =", h)
10 print("------------------------------") """
11
12 return list(newQ), list(sortedH)
13
14 def BestFirst(inState, endState):
15 i=0
16 moves = [U,R,D,L]
17 opened = []
18 closed = []
19 opened.append(inState)
20 heuristics = []
21 heuristics.append(np.count_nonzero((opened[0]==endState)== Fals
22
23 while(i<2000):
24
25 #IF Node == Goal EXIT
26 if(np.count_nonzero((opened[0]==endState)== False)==0):
27 closed.append(opened[0])
28 for x in range (len(closed)):
29 print("Step ", x, " :\n", closed[x], "\n")
30 return print("No. of Steps required = ",i)
31
32 else:
33 temp = opened.pop(0)
34 heuristics.pop(0)
35
36 closed.append(temp)
37
38 #Exploring Neighbours
39 for move in moves:
40 newState = np.copy(temp)
41 newState = move(newState)
42
43 #if (newNode != oldNode)
44 if(np.count_nonzero((newState==temp)== False)>0):
45 #calculate their 'H' value
46 h_val = (np.count_nonzero((newState==endState
47
48 heuristics.append(h_val)
49 opened.append(newState)
50
51 opened, heuristics = rearrange(opened, heuristics)
52
53 i+=1
54 return False
55
56
In [68]: 1 state= np.array([[1,2,3],
2 [5,0,6],
3 [4,7,8],])
4
5 goal = np.array([[1,2,3],
6 [4,5,6],
7 [7,8,0],])
8
9 BestFirst(state, goal)
Step 0 :
[[1 2 3]
[5 0 6]
[4 7 8]]
Step 1 :
[[1 2 3]
[0 5 6]
[4 7 8]]
Step 2 :
[[1 2 3]
[4 5 6]
[0 7 8]]
Step 3 :
[[1 2 3]
[4 5 6]
[7 0 8]]
Step 4 :
[[1 2 3]
[4 5 6]
[7 8 0]]
In [ ]: 1