from __future__ import print_functiongrid = [[0, 1, 0, 0, 0, 0],[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles[0, 1, 0, 0, 0, 0],[0, 1, 0, 0, 1, 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] #all coordinates are given in format [y,x]cost = 1#the cost map which pushes the path closer to the goalheuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]for i in range(len(grid)):for j in range(len(grid[0])):heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])if grid[i][j] == 1:heuristic[i][j] = 99 #added extra penalty in the heuristic map#the actions we can takedelta = [[-1, 0 ], # go up[ 0, -1], # go left[ 1, 0 ], # go down[ 0, 1 ]] # go right#function to search the pathdef search(grid,init,goal,cost,heuristic):closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]# the referrence gridclosed[init[0]][init[1]] = 1action = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]#the action gridx = init[0]y = init[1]g = 0f = g + heuristic[init[0]][init[0]]cell = [[f, g, x, y]]found = False # flag that is set when search is completeresign = False # flag set if we can't find expandwhile not found and not resign:if len(cell) == 0:resign = Truereturn "FAIL"else:cell.sort()#to choose the least costliest action so as to move closer to the goalcell.reverse()next = cell.pop()x = next[2]y = next[3]g = next[1]f = next[0]if x == goal[0] and y == goal[1]:found = Trueelse:for i in range(len(delta)):#to try out different valid actionsx2 = x + delta[i][0]y2 = y + delta[i][1]if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):if closed[x2][y2] == 0 and grid[x2][y2] == 0:g2 = g + costf2 = g2 + heuristic[x2][y2]cell.append([f2, g2, x2, y2])closed[x2][y2] = 1action[x2][y2] = iinvpath = []x = goal[0]y = goal[1]invpath.append([x, y])#we get the reverse path from herewhile x != init[0] or y != init[1]:x2 = x - delta[action[x][y]][0]y2 = y - delta[action[x][y]][1]x = x2y = y2invpath.append([x, y])path = []for i in range(len(invpath)):path.append(invpath[len(invpath) - 1 - i])print("ACTION MAP")for i in range(len(action)):print(action[i])return patha = search(grid,init,goal,cost,heuristic)for i in range(len(a)):print(a[i])
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。