[英]A* Algorithm does not find shortest path
我試圖在python中實現A *算法,但在嘗試查找此映射的路徑時遇到了問題:
X X X X X X X S = Start
0 0 0 X 0 0 0 E = End
0 S 0 X 0 E 0 X = Wall
0 0 0 X 0 0 0
0 0 0 0 0 0 0
我正在使用曼哈頓方法。 我的實現確實找到了一條路徑,但不是最短路徑。 錯誤從第二步開始 - 向右移動后開始。 此時它可以向上移動,啟發式成本將是四(三個右,一個下)或下(三個右,一個上)。 有沒有辦法讓它選擇下來獲得最短的路徑?
碼:
class Node:
def __init__(self, (x, y), g, h, parent):
self.x = x
self.y = y
self.g = g
self.h = h
self.f = g+h
self.parent = parent
def __eq__(self, other):
if other != None:
return self.x == other.x and self.y == other.y
return False
def __lt__(self, other):
if other != None:
return self.f < other.f
return False
def __gt__(self, other):
if other != None:
return self.f > other.f
return True
def __str__(self):
return "(" + str(self.x) + "," + str(self.y) + ") " + str(self.f)
def find_path(start, end, open_list, closed_list, map, no_diag=True, i=1):
closed_list.append(start)
if start == end or start == None:
return closed_list
new_open_list = []
for x, y in [(-1,1),(-1,-1),(1,-1),(1,1),(0,-1),(0,1),(-1,0),(1,0)]:
full_x = start.x + x
full_y = start.y + y
g = 0
if x != 0 and y != 0:
if no_diag:
continue
g = 14
else:
g = 10
h = 10 * (abs(full_x - end.x) + abs(full_y - end.y))
n = Node((full_x,full_y),g,h,start)
if 0 <= full_y < len(map) and 0 <= full_x < len(map[0]) and map[full_y][full_x] != 1 and n not in closed_list:
if n in open_list:
if open_list[open_list.index(n)].g > n.g:
new_open_list.append(n)
else:
new_open_list.append(open_list[open_list.index(n)])
else:
new_open_list.append(n)
if new_open_list == None or len(new_open_list) == 0:
return find_path(start.parent, end, open_list, closed_list, map, no_diag, i-1)
new_open_list.sort()
return find_path(new_open_list[0], end, new_open_list, closed_list, map, no_diag)
您似乎正在為每個節點構建一個新的打開列表,該列表僅包含該節點的鄰居。 這實質上使您的搜索成為深度優先搜索的形式,而A *應該是最好的搜索。
您需要使用一個打開的列表,當您訪問該節點時,該列表將隨每個節點的鄰居進行更新。 打開列表中的舊節點必須保留在那里,直到它們被遍歷並移動到關閉列表中。
關於你在你的問題中所說的,搜索嘗試在向下移動之前是可以的(因為根據啟發式,它們與目標的距離相同)。 重要的是,最終選擇的路徑將是最短的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.