采用boost graph 获取两节点间的路径
时间: 2023-10-06 15:09:27 浏览: 145
使用boost graph库可以很方便地获取两个节点之间的路径。下面是一个示例代码:
```cpp
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
using namespace boost;
int main()
{
typedef adjacency_list<vecS, vecS, directedS,
no_property, property<edge_weight_t, int>> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef graph_traits<Graph>::edge_descriptor Edge;
Graph g(5);
add_edge(0, 1, 2, g);
add_edge(0, 2, 3, g);
add_edge(1, 2, 1, g);
add_edge(1, 3, 2, g);
add_edge(2, 3, 1, g);
add_edge(2, 4, 4, g);
add_edge(3, 4, 2, g);
std::vector<Vertex> p(num_vertices(g)); // 存储最短路径的前驱节点
std::vector<int> d(num_vertices(g)); // 存储最短路径的距离
Vertex start = vertex(0, g);
dijkstra_shortest_paths(g, start,
predecessor_map(make_iterator_property_map(p.begin(), get(vertex_index, g))).
distance_map(make_iterator_property_map(d.begin(), get(vertex_index, g))));
Vertex end = vertex(4, g);
std::cout << "Shortest path from " << start << " to " << end << ": ";
for (Vertex v = end; v != start; v = p[v])
std::cout << v << " <- ";
std::cout << start << std::endl;
return 0;
}
```
这个代码定义了一个有向图,并添加了7条边。然后调用`dijkstra_shortest_paths`函数计算从起点到每个节点的最短路径。最后,通过遍历最短路径的前驱节点,可以得到从起点到终点的路径。
阅读全文