[C++]boost dijkstra获得两点间的最短路
需求是只需要得到两点间的最短路,不需要求得单源对于全图的最短路,使用boost中的dijsktra_shortest_path,当得到目标点的最短路时直接throw exception。
1 #include <boost/config.hpp> 2 #include <iostream> 3 4 #include <boost/graph/graph_traits.hpp> 5 #include <boost/graph/adjacency_list.hpp> 6 #include <boost/graph/dijkstra_shortest_paths.hpp> 7 8 using namespace boost; 9 10 // define visitor for discover_vertex event 11 12 template <class Vertex, class Tag> 13 struct target_visitor : public default_dijkstra_visitor 14 { 15 target_visitor(Vertex u) : v(u) { } 16 17 template <class Graph> 18 void examine_vertex(Vertex u, Graph& g) 19 { 20 if( u == v ) { 21 throw(-1); 22 } 23 } 24 private: 25 Vertex v; 26 }; 27 28 template <class Vertex, class Tag> 29 target_visitor<Vertex, Tag> 30 target_visit(Vertex u, Tag) { 31 return target_visitor<Vertex, Tag>(u); 32 } 33 34 35 int main(int argc, char** argv) 36 { 37 typedef adjacency_list < listS, vecS, directedS, 38 no_property, property < edge_weight_t, int > > graph_t; 39 typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor; 40 typedef graph_traits < graph_t >::edge_descriptor edge_descriptor; 41 typedef std::pair<int, int> Edge; 42 43 const int num_nodes = 5; 44 enum nodes { A, B, C, D, E }; 45 char name[] = "ABCDE"; 46 Edge edge_array[] = 47 { 48 Edge(A, C), Edge(B, B), Edge(B, D), Edge(B, E), 49 Edge(C, B), Edge(C, D), Edge(D, E), Edge(E, A), Edge(E, B) 50 }; 51 int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 }; 52 int num_arcs = sizeof(edge_array) / sizeof(Edge); 53 54 graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes); 55 property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g); 56 57 std::vector<vertex_descriptor> p(num_vertices(g)); 58 std::vector<int> d(num_vertices(g)); 59 60 // choose source and target 61 vertex_descriptor src = vertex(A, g); 62 vertex_descriptor targ = vertex(C, g); 63 64 65 try { 66 dijkstra_shortest_paths(g, src, 67 predecessor_map(&p[0]).distance_map(&d[0]).visitor(target_visit(targ, 68 on_examine_vertex()))); 69 } 70 catch( ... ) { 71 } 72 73 74 std::cout << "distances and parents:" << std::endl; 75 graph_traits < graph_t >::vertex_iterator vi, vend; 76 for (tie(vi, vend) = vertices(g); vi != vend; ++vi) { 77 std::cout << "distance(" << name[*vi] << ") = " << d[*vi] << ", "; 78 std::cout << "parent(" << name[*vi] << ") = " << name[p[*vi]] << std::endl; 79 } 80 81 system("PAUSE"); 82 return EXIT_SUCCESS; 83 }