[英]Shortest path in a grid using BFS
網格由以下項目組成,如python列表列表
g = [
['1', '1', '1', '1', '1'],
['S', '1', 'X', '1', '1'],
['1', '1', '1', '1', '1'],
['X', '1', '1', 'E', '1'],
['1', '1', '1', '1', 'X']
]
S表示開始,E表示結束。
1表示允許的路徑,X表示不允許的路徑
一個簡單的BFS遍歷代碼是
def find_path_bfs(s, e, grid):
queue = list()
path = list()
queue.append(s)
while len(queue) > 0:
node = queue.pop(0)
path.append(node)
mark_visited(node, v)
if node == e:
break
adj_nodes = get_neighbors(node, grid)
for item in adj_nodes:
if is_visited(item, v) is False:
queue.append(item)
return path
據我所知,該算法使用以下輸出正確遍歷
[(1, 0), (1, 1), (2, 0), (0, 0), (2, 1), (0, 1), (2, 1), (0, 1), (2, 2), (3, 1), (0, 2), (2, 2), (3, 1), (0, 2), (2, 3), (3, 2), (3, 2), (4, 1), (0, 3), (2, 3), (3, 2), (3, 2), (4, 1), (0, 3), (2, 4), (3, 3)]
列表中的每個元組代表原始圖中節點的索引。
如何重寫我的BFS代碼以返回最短路徑,而不是返回到達目標節點的整個遍歷路徑? 我已經花費了數小時獨自尋找答案,但到目前為止我一直沒有成功。
為了獲得最短路徑,您還應該將當前節點的路徑也保存在隊列中,因此隊列項的格式為:
(node, path_to_this_node)
修改后的代碼:
def find_path_bfs(s, e, grid):
queue = [(s, [])] # start point, empty path
while len(queue) > 0:
node, path = queue.pop(0)
path.append(node)
mark_visited(node, v)
if node == e:
return path
adj_nodes = get_neighbors(node, grid)
for item in adj_nodes:
if not is_visited(item, v):
queue.append((item, path[:]))
return None # no path found
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.