【问题标题】:Boost dijkstra shortest_path - how can you get the shortest path and not just the distance?Boost dijkstra shortest_path - 如何获得最短路径而不仅仅是距离?
【发布时间】:2012-09-22 10:34:25
【问题描述】:

我需要使用 Boost 库来获得从一个点到另一个点的最短路径。我查看了示例代码,很容易理解。但是,该示例仅显示了如何获取总距离。我试图弄清楚如何迭代前任地图以实际 get 最短路径,但我似乎无法弄清楚。我已经阅读了有关该主题的以下两个问题:

Dijkstra Shortest Path with VertexList = ListS in boost graph

Boost:: Dijkstra Shortest Path, how to get vertice index from path iterator?

但是在提供的两个示例中,IndexMap typedef 似乎无法与 Visual Studio 编译器一起使用,坦率地说,Boost typedef 让我有点困惑,我在弄清楚所有这些方面遇到了一些麻烦。根据此处的 Boost 示例代码,谁能告诉我如何才能摆脱它?我将不胜感激。

http://www.boost.org/doc/libs/1_46_1/libs/graph/example/dijkstra-example.cpp

【问题讨论】:

    标签: c++ boost graph boost-graph


    【解决方案1】:

    如果你只是想从前任地图中获取路径,你可以这样做。

    //p[] is the predecessor map obtained through dijkstra
    //name[] is a vector with the names of the vertices
    //start and goal are vertex descriptors
    std::vector< graph_traits< graph_t >::vertex_descriptor > path;
    graph_traits< graph_t >::vertex_descriptor current=goal;
    
    while(current!=start) {
        path.push_back(current);
        current=p[current];
    }
    path.push_back(start);
    
    //This prints the path reversed use reverse_iterator and rbegin/rend
    std::vector< graph_traits< graph_t >::vertex_descriptor >::iterator it;
    for (it=path.begin(); it != path.end(); ++it) {
    
        std::cout << name[*it] << " ";
    }
    std::cout << std::endl;
    

    【讨论】:

    • 注意 - 我认为你必须添加 path.push_back(current);就在您到达最终路径之前。push_back(start); - 当我使用它时,它总是忘记最后一个节点之前的节点。
    • @Darkenor 很抱歉,我相信它现在可以正常工作了。
    • 感谢有用的 sn-p!修改这段代码是否也很难显示各个路段的距离?
    • 出色的答案,许多文档似乎都错过了这部分难题。谢谢。
    【解决方案2】:

    这是llonesmiz's code 稍作修改以显示从 A 到其他节点的中间段以及段距离:

    输出

    A[0] C[1] D[3] E[1] B[1] 
    A[0] C[1] 
    A[0] C[1] D[3] 
    A[0] C[1] D[3] E[1]
    

    代码

    // DISPLAY THE PATH TAKEN FROM A TO THE OTHER NODES
    
    nodes  start = A;
    for ( int goal=B; goal<=E; ++goal )
    {
      std::vector< graph_traits< graph_t >::vertex_descriptor >  path;
      graph_traits< graph_t >::vertex_descriptor                 current=goal;
    
      while( current!=start )
      {
        path.push_back( current );
        current = p[current];
      }
      path.push_back( start );
    
      // rbegin/rend will display from A to the other nodes
      std::vector< graph_traits< graph_t >::vertex_descriptor >::reverse_iterator rit;
      int cum=0;
      for ( rit=path.rbegin(); rit!=path.rend(); ++rit) 
      {
        std::cout << name[*rit] << "[" << d[*rit]-cum << "] ";
        cum = d[*rit];
      }
      std::cout << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-19
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多