【问题标题】:Boost's Dijkstra's Algorithm TutorialBoost 的 Dijkstra 算法教程
【发布时间】:2012-07-28 10:29:39
【问题描述】:

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

[Boost 的文档:http://www.boost.org/doc/libs/1_50_0/libs/graph/doc/dijkstra_shortest_paths.html] [Dijkstra 示例:http://www.boost.org/doc/libs/1_36_0/libs/graph/example/dijkstra-example.cpp]

有人可以通过代码示例提供一步一步的解释来展示如何使用 Boost 的 Dijkstra 算法吗? 我正在为我的图表使用 Boost 的 adjacency_list,就像上面的示例链接一样。 (adjacency_list:http://www.boost.org/doc/libs/1_50_0/libs/graph/doc/adjacency_list.html)

【问题讨论】:

  • 发布一些你尝试过但没有奏效的例子。
  • "..their example and documentation" - 你在使用谁的示例和文档?
  • 确定一下,您完全了解 Dijkstra 算法吗?
  • @hatchet 我发布了上面示例和文档的链接。

标签: c++ visual-c++ boost dijkstra


【解决方案1】:

关于cmets中的问题:

  1. 根据示例 VC++ 源代码中的注释,named parameter mechanism used 存在一些问题。因此,我假设这两个分支的想法基本相同,只是 VC++ 版本更冗长(不过我没有深入研究它足够长的时间来 100% 确定)。
  2. property_map 将顶点/边映射到与特定顶点/边关联的附加数据。例如。示例中的 weightmap 将权重(旅行成本)与每条边相关联。
  3. predecessor_map 用于记录所有顶点的路径(对于每个顶点,记录从根开始的路径上的前驱)。至于为什么需要它:嗯,这些信息是人们经常希望从算法中得到的东西。

  4. description 中明确列出了参数。请注意这两个版本,一个带有命名参数,一个没有(后者在 VC++ 中使用)。

现在逐步了解the documentation 中给出的示例代码(请注意,我从未真正使用过Boost.Graph,所以这不能保证正确性,我也只包含了相关部分并省略了@987654328 @ VC++):

  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]));

正如我个人在 cmets 中提到的,我发现 lemon 使用起来比 Boost.Graph 更直观,所以也许你可能想看看它

【讨论】:

  • @user1563613:如果您发现答案有帮助,那么表示感谢的典型方式就是接受和/或支持它
猜你喜欢
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 2011-06-27
  • 2021-07-10
相关资源
最近更新 更多