importrandom
grid=[[0,1,0,0,0,0],[0,1,0,0,0,0],[0,1,0,0,0,0],[0,1,0,0,0,0],[0,0,0,0,1,0]]heuristic=[[9,8,7,6,5,4],[8,7,6,5,4,3],[7,6,5,4,3,2],[6,5,4,3,2,1],[5,4,3,2,1,0]]init=[0,0]goal=[len(grid)-1,len(grid[0])-1]#Below the four potential actions to the single fielddelta=[[-1,0],#up[0,-1],#left[1,0],#down[0,1]]#rightdelta_name=['^','']#The name of above actionscost=1defsearch():#open list elements are of the type [g,x,y]closed=[[0forrowinrange(len(grid[0]))]forcolinrange(len(grid))]action=[[-1forrowinrange(len(grid[0]))]forcolinrange(len(grid))]#We initialize the starting location as checkedclosed[init[0]][init[1]]=1expand=[[-1forrowinrange(len(grid[0]))]forcolinrange(len(grid))]# we assigned the cordinates and g valuex=init[0]y=init[1]g=0h=heuristic[x][y]f=g+h#our open list will contain our initial valueopen=[[f,g,h,x,y]]found=False#flag that is set when search completeresign=False#Flag set if we can't find expandcount=0#print('initial open list:')#for i in range(len(open)):#print(' ', open[i])#print('----')whilefoundisFalseandresignisFalse:#Check if we still have elements in the open listiflen(open)==0:#If our open list is empty, there is nothing to expand.resign=Trueprint('Fail')print('############# Search terminated without success')print()else:#if there is still elements on our list#remove node from listopen.sort()#sort elements in an increasing order from the smallest g value upopen.reverse()#reverse the listnext=open.pop()#remove the element with the smallest g value from the list#print('list item')#print('next')#Then we assign the three values to x,y and g. Which is our expantion.x=next[3]y=next[4]g=next[1]expand[x][y]=count
count+=1#Check if we are doneifx==goal[0]andy==goal[1]:found=Trueprint(next)#The three elements above this "if".print('############## Search is success')print()else:#expand winning element and add to new open listforiinrange(len(delta)):#going through all our actions the four actions#We apply the actions to x and y with additional delta to construct x2 and y2x2=x+delta[i][0]y2=y+delta[i][1]#if x2 and y2 falls into the gridifx2>=0andx2=0andy2<=len(grid[0])-1:ifclosed[x2][y2]==0andgrid[x2][y2]==0:g2=g+cost
h2=heuristic[x2][y2]f2=g2+h2
open.append([f2,g2,h2,x2,y2])#print('append list item')#print([g2,x2,y2])#Then we check them to never expand againclosed[x2][y2]=1action[x2][y2]=iforiinrange(len(expand)):print(expand[i])print()policy=[[' 'forrowinrange(len(grid[0]))]forcolinrange(len(grid))]x=goal[0]y=goal[1]policy[x][y]='*'whilex!=init[0]ory!=init[1]:x2=x-delta[action[x][y]][0]y2=y-delta[action[x][y]][1]policy[x2][y2]=delta_name[action[x][y]]x=x2
y=y2foriinrange(len(policy)):print(policy[i])search()