到某个点的最短距离 到终点的最短路径
完整代码
1 #include <iostream> 2 #include <string> 3 #include <utility> 4 #include <vector> 5 #include <deque> 6 #include <boost/graph/adjacency_list.hpp> 7 //A*寻路算法 8 #include <boost\graph\astar_search.hpp> 9 #include <boost\graph\dijkstra_shortest_paths.hpp> 10 using namespace std; 11 using namespace boost; 12 13 14 void main() 15 { 16 //定义图的种类 17 typedef adjacency_list<listS, vecS, directedS, no_property, property<edge_weight_t, double>> graph_t; 18 //定义相关类型 19 typedef graph_traits<graph_t>::vertex_descriptor vertex_desciptor; 20 typedef graph_traits<graph_t>::edge_descriptor edge_descriptor; 21 typedef pair<int, int> Edge; 22 23 //定义结点和边的相关对象和属性 24 enum nodes { A, B, C, D, E, F, G, H, N }; 25 char name[] = "ABCDEFGH"; 26 //创建边 27 Edge edge_array[] = { Edge(A,B),Edge(A,C),Edge(B,D),Edge(B,E),Edge(C,E), 28 Edge(C,F),Edge(F,G),Edge(G,H),Edge(E,H),Edge(D,E),Edge(D,H) }; 29 //定义边的权重 30 double weights[] = { 5,1,1.3,3,10,2,1.2,0.5,1.3,0.4,6.3 }; 31 //边的数量 32 int num_arcs = sizeof(edge_array) / sizeof(Edge); 33 34 //生成被建模的图对象 35 // 边数组头地址 边数组尾地址 定义权重 结点数量 36 graph_t g(edge_array, edge_array + num_arcs, weights, N); 37 38 //p用于放置最短路径生成树的各个顶点的下一个节点 39 std::vector<vertex_desciptor> p(num_vertices(g)); 40 //d用于放置从近到远的路径距离 41 std::vector<double> d(num_vertices(g)); 42 //待求最短路径的源顶点 43 vertex_desciptor s = vertex(A, g); 44 45 //对图g的A顶点(s为它的描述器,即从哪个点开始)应用dijkstra算法 46 //作为结果的距离矢量保存在d数组中 47 //最短路径树上的父节点保存在p数组中 48 dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0])); 49 std::cout << "最短路径延时(ms)" << "\t最短路径树的父节点:" << std::endl; 50 //输出结果到屏幕 51 graph_traits <graph_t>::vertex_iterator vi, vend; 52 for (tie(vi, vend) = vertices(g); vi != vend; vi++) 53 { 54 std::cout << "路径距离(" << name[*vi] << ") = " << d[*vi] << ",\t"; 55 std::cout << "父节点(" << name[*vi] << ") = " << name[p[*vi]] << endl; 56 } 57 cout << endl; 58 system("pause"); 59 }
原文地址:https://www.cnblogs.com/xiaochi/p/8673240.html
时间: 2024-09-30 04:00:21