Dijkstra’s Shortest Paths
Solves the single-source shortest-paths problem on a weighted, directed or undirected graph for the case where all edge weights are nonnegative.
Complexity: O(V log V + E)
Defined in: <boost/graph/dijkstra_shortest_paths.hpp>
Example
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/visitors.hpp>
#include <iostream>
#include <limits>
#include <vector>
struct City {};
struct Road { int cost; };
using namespace boost;
using Graph = adjacency_list<vecS, vecS, directedS, City, Road>;
using Vertex = graph_traits<Graph>::vertex_descriptor;
int main() {
Graph g(4);
add_edge(0, 1, Road{1}, g);
add_edge(1, 2, Road{2}, g);
add_edge(0, 2, Road{10}, g);
add_edge(2, 3, Road{1}, g);
// Storage: you control allocation, lifetime, and container type
std::vector<Vertex> storage_pred(num_vertices(g));
std::vector<int> storage_dist(num_vertices(g));
// Property maps: lightweight views into the storage
auto index_map = get(vertex_index, g);
auto costs_map = get(&Road::cost, g);
auto predecessor_map = make_iterator_property_map(storage_pred.begin(), index_map);
auto distance_map = make_iterator_property_map(storage_dist.begin(), index_map);
dijkstra_shortest_paths(g, vertex(0, g),
predecessor_map, distance_map,
costs_map, index_map,
std::less<int>(), std::plus<int>(),
std::numeric_limits<int>::max(), 0,
dijkstra_visitor<null_visitor>());
for (auto v : make_iterator_range(vertices(g)))
std::cout << "distance to " << v << " = " << storage_dist[v] << "\n";
}
distance to 0 = 0
distance to 1 = 1
distance to 2 = 3
distance to 3 = 4
(1) Positional version
template <typename Graph, typename DijkstraVisitor, typename PredecessorMap,
typename DistanceMap, typename WeightMap, typename VertexIndexMap,
typename CompareFunction, typename CombineFunction,
typename DistInf, typename DistZero, typename ColorMap = default>
void dijkstra_shortest_paths(
const Graph& g,
typename graph_traits<Graph>::vertex_descriptor s,
PredecessorMap predecessor, DistanceMap distance,
WeightMap weight, VertexIndexMap index_map,
CompareFunction compare, CombineFunction combine,
DistInf inf, DistZero zero,
DijkstraVisitor vis, ColorMap color = default);
| Direction | Parameter | Description |
|---|---|---|
IN |
|
The graph object on which the algorithm will be applied.
The type |
IN |
|
The source vertex. All distances will be calculated from this vertex, and the shortest paths tree will be rooted at this vertex. |
OUT |
|
The predecessor map records the edges in the shortest path tree, the
tree computed by the traversal of the graph. Upon completion of the
algorithm, the edges (p[u],u) for all u in V are in the
tree. The shortest path from vertex s to each vertex v in the graph
consists of the vertices v, p[v], p[p[v]], and
so on until s is reached, in reverse order. The tree is not guaranteed
to be a minimum spanning tree. If p[u] = u then u is either
the source vertex or a vertex that is not reachable from the source. The
|
UTIL/OUT |
|
The shortest path weight from the source vertex |
IN |
|
The weight or "length" of each edge in the graph. The weights must
all be non-negative, and the algorithm will throw a
|
IN |
|
This maps each vertex to an integer in the range |
IN |
|
This function is used to compare distances to determine which vertex
is closer to the source vertex. The |
IN |
|
This function is used to combine distances to compute the distance of a
path. The |
IN |
|
The |
IN |
|
The |
IN |
|
Use this to specify actions that you would like to happen during certain
event points within the algorithm. The type |
UTIL/OUT |
|
This is used during the execution of the algorithm to mark the vertices.
The vertices start out white and become gray when they are inserted in
the queue. They then turn black when they are removed from the queue. At
the end of the algorithm, vertices reachable from the source vertex will
have been colored black. All other vertices will still be white. The
type |
(2) No-init version
template <class Graph, class DijkstraVisitor, class PredecessorMap,
class DistanceMap, class WeightMap, class IndexMap,
class Compare, class Combine, class DistZero, class ColorMap>
void dijkstra_shortest_paths_no_init(
const Graph& g,
typename graph_traits<Graph>::vertex_descriptor s,
PredecessorMap predecessor, DistanceMap distance,
WeightMap weight, IndexMap index_map,
Compare compare, Combine combine, DistZero zero,
DijkstraVisitor vis, ColorMap color = default);
Same parameters as (1), but does not initialize the property maps (except for the default color map). Use this when you want to control initialization yourself.
(3) Named parameter version
template <typename Graph, typename P, typename T, typename R>
void dijkstra_shortest_paths(
Graph& g,
typename graph_traits<Graph>::vertex_descriptor s,
const bgl_named_params<P, T, R>& params);
| Direction | Parameter | Description |
|---|---|---|
IN |
|
The graph object. Must model Vertex List Graph and Incidence Graph. |
IN |
|
The source vertex. All distances will be calculated from this vertex. |
IN |
|
Named parameters passed via |
| Direction | Named Parameter | Description / Default |
|---|---|---|
IN |
|
Edge weights (see (1) |
IN |
|
Vertex-to-integer mapping (see (1) |
OUT |
|
Predecessor map (see (1) |
UTIL/OUT |
|
Distance map (see (1) |
IN |
|
Distance comparison function (see (1) |
IN |
|
Distance combination function (see (1) |
IN |
|
Infinity value (see (1) |
IN |
|
Identity element (see (1) |
UTIL/OUT |
|
Color map (see (1) |
OUT |
|
Visitor (see (1) |
Description
solves the single-source shortest-paths problem on a weighted, directed or undirected graph for the case where all edge weights are nonnegative. Use the Bellman-Ford algorithm for the case when some edge weights are negative. Use breadth-first search instead of Dijkstra’s algorithm when all edge weights are equal to one. For the definition of the shortest-path problem see Section Shortest-Paths Algorithms for some background to the shortest-path problem.
There are two main options for obtaining output from the
dijkstra_shortest_paths() function. If you provide a distance
property map through the distance_map() parameter then the
shortest distance from the source vertex to every other vertex in the
graph will be recorded in the distance map. Also you can record the
shortest paths tree in a predecessor map: for each vertex u in V,
p[u] will be the predecessor of u in the shortest paths tree
(unless p[u] = u, in which case u is either the source or a
vertex unreachable from the source). In addition to these two options,
the user can provide their own custom-made visitor that takes actions
during any of the algorithm’s event points.
Dijkstra’s algorithm finds all the shortest paths from the source vertex to every other vertex by iteratively "growing" the set of vertices S to which it knows the shortest path. At each step of the algorithm, the next vertex added to S is determined by a priority queue. The queue contains the vertices in V - S [1] prioritized by their distance label, which is the length of the shortest path seen so far for each vertex. The vertex u at the top of the priority queue is then added to S, and each of its out-edges is relaxed: if the distance to u plus the weight of the out-edge (u,v) is less than the distance label for v then the estimated distance for vertex v is reduced. The algorithm then loops back, processing the next vertex at the top of the priority queue. The algorithm finishes when the priority queue is empty.
The algorithm uses color markers (white, gray, and black) to keep track
of which set each vertex is in. Vertices colored black are in S.
Vertices colored white or gray are in V-S. White vertices have not yet
been discovered and gray vertices are in the priority queue. By default,
the algorithm will allocate an array to store a color marker for each
vertex in the graph. You can provide your own storage and access for
colors with the color_map() parameter.
Pseudo-Code
The following is the pseudo-code for Dijkstra’s single-source shortest paths algorithm. w is the edge weight, d is the distance label, and p is the predecessor of each vertex which is used to encode the shortest paths tree. Q is a priority queue that supports the DECREASE-KEY operation. The visitor event points for the algorithm are indicated by the labels on the right.
|
|
Visitor Event Points
-
vis.initialize_vertex(u, g)is invoked on each vertex in the graph before the start of the algorithm. -
vis.examine_vertex(u, g)is invoked on a vertex as it is removed from the priority queue and added to set S. At this point we know that (p[u],u) is a shortest-paths tree edge so d[u] = delta(s,u) = d[p[u]] + w(p[u],u). Also, the distances of the examined vertices is monotonically increasing d[u1] <= d[u2] <= d[un]. -
vis.examine_edge(e, g)is invoked on each out-edge of a vertex immediately after it has been added to set S. -
vis.edge_relaxed(e, g)is invoked on edge (u,v) if d[u] + w(u,v) < d[v]. The edge (u,v) that participated in the last relaxation for vertex v is an edge in the shortest paths tree. -
vis.discover_vertex(v, g)is invoked on vertex v when the edge (u,v) is examined and v is WHITE. Since a vertex is colored GRAY when it is discovered, each reachable vertex is discovered exactly once. This is also when the vertex is inserted into the priority queue. -
vis.edge_not_relaxed(e, g)is invoked if the edge is not relaxed (see above). -
vis.finish_vertex(u, g)is invoked on a vertex after all of its out edges have been examined.
Notes
[1] The algorithm used here saves a little space by not putting all V - S vertices in the priority queue at once, but instead only those vertices in V - S that are discovered and therefore have a distance less than infinity.
[2] Since the visitor parameter is passed by value, if your visitor contains state then any changes to the state during the algorithm will be made to a copy of the visitor object, not the visitor object passed in. Therefore you may want the visitor to hold this state by pointer or reference.