【发布时间】:2022-01-13 09:59:04
【问题描述】:
最近我参加了算法理论的考试。我有一个正常的最佳优先搜索算法(代码如下)。
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(路径总和 - 8),是正确的。
我的老师建议我重新编写代码,以便它查找本地最小路径,即Path: 0 1 2(路径总和 - 13)。
我需要贪婪地从当前节点到未访问节点的最短边,我真的不明白如何正确地做。
【问题讨论】:
-
你想要最短路径,即 Dijkstra 算法吗?还是想贪婪地取当前节点到未访问节点的最短边?现在你的代码介于两者之间,问题和示例也没有明确你想要什么。
-
@Thomas,贪婪地取从当前节点到未访问节点的最短边。
标签: python algorithm data-structures graph best-first-search