[英]Find local shortest path with greedy best first search algorithm
最近我參加了算法理論的考試。 我有一個正常的最佳優先搜索算法(下面的代碼)。
from queue import PriorityQueue
# Filling adjacency matrix with empty arrays
vertices = 14
graph = [[] for i in range(vertices)]
# Function for adding edges to graph
def add_edge(x, y, cost):
graph[x].append((y, cost))
graph[y].append((x, cost))
# Function For Implementing Best First Search
# Gives output path having the lowest cost
def best_first_search(source, target, vertices):
visited = [0] * vertices
pq = PriorityQueue()
pq.put((0, source))
print("Path: ")
while not pq.empty():
u = pq.get()[1]
# Displaying the path having the lowest cost
print(u, end=" ")
if u == target:
break
for v, c in graph[u]:
if not visited[v]:
visited[v] = True
pq.put((c, v))
print()
if __name__ == '__main__':
# The nodes shown in above example(by alphabets) are
# implemented using integers add_edge(x,y,cost);
add_edge(0, 1, 1)
add_edge(0, 2, 8)
add_edge(1, 2, 12)
add_edge(1, 4, 13)
add_edge(2, 3, 6)
add_edge(4, 3, 3)
source = 0
target = 2
best_first_search(source, target, vertices)
他帶出Path: 0 1 0 2
(path sum — 8),它是正確的。
我的老師建議我重新編寫代碼,以便它尋找局部最小路徑,即Path: 0 1 2
(path sum — 13)。
我需要貪婪地從當前節點到未訪問節點的最短邊,我真的不明白如何正確地做到這一點。
由於這是家庭作業,我不會為您拼出整個代碼。
對於最佳優先搜索,您不需要優先級隊列。 您只需要跟蹤您訪問過哪些節點,以及您當前所在的節點。 雖然您的當前節點不是目標節點,但找到通向未訪問節點的最短邊,並將當前節點設置為該邊另一端的節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.