【问题标题】:Find local shortest path with greedy best first search algorithm使用贪心最佳优先搜索算法找到局部最短路径
【发布时间】: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


【解决方案1】:

由于这是作业,我不会为你拼出整个代码。

对于最佳优先搜索,您不需要优先级队列。您只需要跟踪您访问过哪些节点,以及您当前所在的节点。虽然您的当前节点不是目标节点,但找到通向未访问节点的最短边,并将当前节点设置为该边另一端的节点。

【讨论】:

  • 但是为什么我不需要优先队列呢?
  • 很遗憾,我不太擅长算法。
  • 为什么你需要一个优先队列?您只需要每个节点一次的最小长度边,每个节点独立。在 things 列表中找到最小的 thing 并不需要像 PQ 那样复杂的东西。
猜你喜欢
  • 2013-12-03
  • 2012-01-12
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
相关资源
最近更新 更多