1 //=======================================================================
2 // Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See
5 // accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
7 //=======================================================================
8 #include <boost/config.hpp>
9 #include <iostream>
10 #include <fstream>
11
12 #include <boost/graph/graph_traits.hpp>
13 #include <boost/graph/adjacency_list.hpp>
14 #include <boost/graph/dijkstra_shortest_paths.hpp>
15 #include <boost/property_map/property_map.hpp>
16
17 using namespace boost;
18
main(int,char * [])19 int main(int, char*[])
20 {
21 typedef adjacency_list< listS, vecS, directedS, no_property,
22 property< edge_weight_t, int > >
23 graph_t;
24 typedef graph_traits< graph_t >::vertex_descriptor vertex_descriptor;
25 typedef std::pair< int, int > Edge;
26
27 const int num_nodes = 5;
28 enum nodes
29 {
30 A,
31 B,
32 C,
33 D,
34 E
35 };
36 char name[] = "ABCDE";
37 Edge edge_array[] = { Edge(A, C), Edge(B, B), Edge(B, D), Edge(B, E),
38 Edge(C, B), Edge(C, D), Edge(D, E), Edge(E, A), Edge(E, B) };
39 int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 };
40 int num_arcs = sizeof(edge_array) / sizeof(Edge);
41 graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);
42 property_map< graph_t, edge_weight_t >::type weightmap
43 = get(edge_weight, g);
44 std::vector< vertex_descriptor > p(num_vertices(g));
45 std::vector< int > d(num_vertices(g));
46 vertex_descriptor s = vertex(A, g);
47
48 dijkstra_shortest_paths(g, s,
49 predecessor_map(boost::make_iterator_property_map(
50 p.begin(), get(boost::vertex_index, g)))
51 .distance_map(boost::make_iterator_property_map(
52 d.begin(), get(boost::vertex_index, g))));
53
54 std::cout << "distances and parents:" << std::endl;
55 graph_traits< graph_t >::vertex_iterator vi, vend;
56 for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi)
57 {
58 std::cout << "distance(" << name[*vi] << ") = " << d[*vi] << ", ";
59 std::cout << "parent(" << name[*vi] << ") = " << name[p[*vi]]
60 << std::endl;
61 }
62 std::cout << std::endl;
63
64 std::ofstream dot_file("figs/dijkstra-eg.dot");
65
66 dot_file << "digraph D {\n"
67 << " rankdir=LR\n"
68 << " size=\"4,3\"\n"
69 << " ratio=\"fill\"\n"
70 << " edge[style=\"bold\"]\n"
71 << " node[shape=\"circle\"]\n";
72
73 graph_traits< graph_t >::edge_iterator ei, ei_end;
74 for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
75 {
76 graph_traits< graph_t >::edge_descriptor e = *ei;
77 graph_traits< graph_t >::vertex_descriptor u = source(e, g),
78 v = target(e, g);
79 dot_file << name[u] << " -> " << name[v] << "[label=\""
80 << get(weightmap, e) << "\"";
81 if (p[v] == u)
82 dot_file << ", color=\"black\"";
83 else
84 dot_file << ", color=\"grey\"";
85 dot_file << "]";
86 }
87 dot_file << "}";
88 return EXIT_SUCCESS;
89 }
90