提升dijkstra shortest_path - 你怎么能得到最短路径而不仅仅是距离?

时间:2012-10-01 14:49:07

标签: c++ boost graph boost-graph

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

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

2 个答案:

答案 0 :(得分:10)

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

//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;

答案 1 :(得分: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]

<强> CODE

// 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;
}