【问题标题】:Algorithm that sorts the vertices in a graph by their distance from the source根据与源的距离对图中的顶点进行排序的算法
【发布时间】:2014-02-12 03:50:36
【问题描述】:

我在数据结构课程中有以下问题,我想知道我的解决方案是否正确。

令 G(V,E) 是一个连通的无向图,使得 |V|=m 和 |E|=n。每个顶点都有其唯一的名称(从 1 到 n)。现在给定一个源顶点 S,我需要按与 S 的距离对所有顶点进行排序,然后打印它们。复杂度 O(m+n)

我的解决方案(理论上):

我基本上会使用 BFS 伪代码,我会在 while 循环的末尾添加以下命令,例如在将当前顶点 'u' 涂黑之前:

入队(Q2,u)。

然后我将有一个可以打印的排序队列 Q2。

你认为它正确吗? 非常感谢!

【问题讨论】:

  • 不是从 s 到图的所有节点的最短路径算法 (Dijkstra) 吗?

标签: algorithm data-structures


【解决方案1】:

如果您的边是成本加权的,那么您将需要使用 Dijkstra 算法而不是广度优先。否则,是的,那个方法很好。

【讨论】:

    【解决方案2】:

    您描述的问题已由Dijkstra algorithm 解决。它基本上取最近的尚未访问过的节点,并记下到最接近它的所有节点的距离:

    1. start from the source node S
    2. add all neighboring nodes into a list, ordered by their distance 
       and write down the current shortest distance to them
    3. pick the closest node N
    4. update the distances of all already visited nodes, if a shorter distance
       is available to them through N
    5. add remaining neighboring nodes into the list
    6. eliminate N from the list and repeat from step 3.
    

    必须按照从最近到最远的顺序访问节点,以免错过任何可能的最短路径。

    实现 Dijkstra 的挑战是优先级前端的实现,它存储节点,按它们与源的距离排序。如果使用简单列表,还需要考虑到数组中新节点的输入,因为需要找到元素的正确位置。

    因此对基本的 Dijkstra 进行了多项改进,例如使用Fibonacci heap 作为实现优先级队列的结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2021-10-25
      • 2021-01-23
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多