我以两种方式在 Python 中实现了贪婪的最佳优先搜索算法。在第一个中,使用优先级队列,在第二个中,在 while 循环结束时对列表 to_visit 进行排序(将具有启发式函数最佳结果的元素放在最后,以便下次弹出它)。而且我无法弄清楚这两者之间的区别是什么,因为我为带有 sort. 这是我的代码:
对于有排序的:
def searchGreedy(mapM, initialX, initialY, finalX, finalY):
found = False
start = (initialX, initialY)
goal = (finalX, finalY)
visited = []
to_visit = []
came_from = {} #parent dictionary
to_visit.append(start)
came_from[start] = None
while len(to_visit) != 0 and not found:
if not to_visit:
return False
current = to_visit[-1]
visited.append(current)
x, y = current
del to_visit[-1]
if current == goal:
found = True
else:
aux = []
neighbors = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
for next in neighbors:
if next not in visited and is_inside(next, mapM) and is_not_wall(next, mapM):
aux.append(next)
came_from[next] = (x, y)
to_visit += aux
to_visit.sort(key = lambda point: manhattan_distance(point, goal), reverse=True)
if found:
return get_path(goal, start, came_from)
else:
return None
这是具有优先级队列的:
def searchGreedyPQ(mapM, initialX, initialY, finalX, finalY):
found = False
start = (initialX, initialY)
goal = (finalX, finalY)
visited = []
to_visit = PriorityQueue() # FIFO sorted list
came_from = {} # parent dictionary
to_visit.put((0, start))
came_from[start] = None
while not to_visit.empty() and not found:
current = to_visit.get()[1]
visited.append(current)
x, y = current
if current == goal:
found = True
else:
neighbors = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
for next in neighbors:
if next not in visited and is_inside(next, mapM) and is_not_wall(next, mapM):
priority = manhattan_distance(next, goal)
to_visit.put((priority, next))
came_from[next] = (x, y)
if found:
return get_path(goal, start, came_from)
else:
return None
我看到了相同的执行,但我不明白为什么排序的人会找到步数更少(更优化)的路径。
有人可以向我解释一下,或建议我应该改变什么吗?