首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Boost的Dijkstra算法教程

Boost的Dijkstra算法教程
EN

Stack Overflow用户
提问于 2012-07-31 01:52:11
回答 1查看 8.3K关注 0票数 7

我很难弄清楚如何使用Boost的Dijkstra算法。我已经看过了他们的示例和文档,但我仍然不明白如何使用它。

Boost文档: http://www.boost.org/doc/libs/1_50_0/libs/graph/doc/dijkstra_shortest_paths.html

有没有人可以用代码示例一步一步地解释一下如何使用Boost的Dijkstra算法?我将Boost的adjacency_list用于我的图形,就像上面的示例链接一样。(adjacency_list:http://www.boost.org/doc/libs/1_50_0/libs/graph/doc/adjacency_list.html)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-02 06:53:27

关于评论中的问题:

  1. 根据示例VC++源代码中的注释,named parameter mechanism used存在一些问题。因此,我假设这两个分支基本上做了相同的思考,只是VC++版本更冗长(尽管我没有深入研究足够长的时间以100%确定)。
  2. A property_map将顶点/边映射到与特定顶点/边关联的额外数据。例如,示例中的weightmap将权重(旅行成本)与每条边相关联。
  3. predecessor_map用于记录所有顶点的路径(对于每个顶点,记录从根开始的路径上的前一个顶点)。至于为什么需要它:嗯,人们通常希望从算法中获得这些信息。
  4. description中清楚地列出了这些参数。注意两个版本,一个有命名参数,另一个没有(后者在VC++中使用)。

现在,对于the documentation中给出的示例代码进行了一些循序渐进的介绍(请注意,我实际上从未使用过Boost.Graph,所以这不能保证正确性,而且我只包含了相关部分,并省略了VC++的#if ):

代码语言:javascript
复制
  const int num_nodes = 5;
  //names of graph nodes
  enum nodes { A, B, C, D, E };
  char name[] = "ABCDE";
  //edges of the graph
  Edge edge_array[] = { Edge(A, C), Edge(B, B), Edge(B, D), Edge(B, E),
    Edge(C, B), Edge(C, D), Edge(D, E), Edge(E, A), Edge(E, B)
  };
  //weights/travelling costs for the edges
  int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 };
  int num_arcs = sizeof(edge_array) / sizeof(Edge);

  //graph created from the list of edges
  graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);
  //create the property_map from edges to weights
  property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);

  //create vectors to store the predecessors (p) and the distances from the root (d)
  std::vector<vertex_descriptor> p(num_vertices(g));
  std::vector<int> d(num_vertices(g));
  //create a descriptor for the source node
  vertex_descriptor s = vertex(A, g);

  //evaluate dijkstra on graph g with source s, predecessor_map p and distance_map d
  //note that predecessor_map(..).distance_map(..) is a bgl_named_params<P, T, R>, so a named parameter
  dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));

正如我在评论中亲自提到的那样,我发现使用lemon比使用Boost.Graph更直观,所以您可能想要看一看它

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11726857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档