ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 3.8 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | FAIL | meta_canonical IS NULL OR = '' OR = src_unparsed | org,boost!www,/doc/libs/latest/libs/graph/doc/bellman_ford_shortest.html s443 |
| Property | Value |
|---|---|
| URL | https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/bellman_ford_shortest.html |
| Last Crawled | 2025-12-14 22:41:42 (3 months ago) |
| First Indexed | 2018-12-16 14:33:44 (7 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Bellman Ford Shortest Paths |
| Meta Description | null |
| Meta Canonical | org,boost!www,/doc/libs/latest/libs/graph/doc/bellman_ford_shortest.html s443 |
| Boilerpipe Text | Bellman Ford Shortest Paths // named paramter version
template <class EdgeListGraph , class Size, class P, class T, class R>
bool bellman_ford_shortest_paths(const EdgeListGraph& g, Size N,
const bgl_named_params<P, T, R>& params = all defaults );
template <class VertexAndEdgeListGraph , class P, class T, class R>
bool bellman_ford_shortest_paths(const VertexAndEdgeListGraph& g,
const bgl_named_params<P, T, R>& params = all defaults );
// non-named parameter version
template <class EdgeListGraph , class Size, class WeightMap,
class PredecessorMap, class DistanceMap,
class BinaryFunction , class BinaryPredicate ,
class BellmanFordVisitor >
bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N,
WeightMap weight, PredecessorMap pred, DistanceMap distance,
BinaryFunction combine, BinaryPredicate compare, BellmanFordVisitor v)
The Bellman-Ford algorithm [ 4 , 11 , 20 , 8 ] solves the single-source
shortest paths problem for a graph with both positive and negative
edge weights. For the definition of the shortest paths problem see
Section Shortest-Paths
Algorithms .
If you only need to solve the shortest paths problem for positive edge
weights, Dijkstra's algorithm provides a more efficient
alternative. If all the edge weights are all equal to one then breadth-first
search provides an even more efficient alternative.
Before calling the bellman_ford_shortest_paths() function,
the user must assign the source vertex a distance of zero and all
other vertices a distance of infinity unless you are providing
a starting vertex. The Bellman-Ford algorithm
proceeds by looping through all of the edges in the graph, applying
the relaxation operation to each edge. In the following pseudo-code,
v is a vertex adjacent to u , w maps edges to
their weight, and d is a distance map that records the length
of the shortest path to each vertex seen so far. p is a
predecessor map which records the parent of each vertex, which will
ultimately be the parent in the shortest paths tree
RELAX( u , v , w , d , p )
if ( w(u,v) + d[u] < d[v] )
d[v] := w(u,v) + d[u] p[v] := u else
...
relax edge (u,v)
edge (u,v) is not relaxed
The algorithm repeats this loop |V| times after which it is
guaranteed that the distances to each vertex have been reduced to the
minimum possible unless there is a negative cycle in the graph. If
there is a negative cycle, then there will be edges in the graph that
were not properly minimized. That is, there will be edges (u,v) such
that w(u,v) + d[u] < d[v] . The algorithm loops over the edges in
the graph one final time to check if all the edges were minimized,
returning true if they were and returning false
otherwise.
BELLMAN-FORD( G )
// Optional initialization for each vertex u in V d[u] := infinity p[u] := u end for for i := 1 to |V|-1 for each edge (u,v) in E
RELAX( u , v , w , d , p )
end for end for for each edge (u,v) in E if ( w(u,v) + d[u] < d[v] )
return (false, , )
else
...
end for return (true, p , d )
examine edge (u,v)
edge (u,v) was not minimized
edge (u,v) was minimized
There are two main options for obtaining output from the
bellman_ford_shortest_paths() function. If the user provides
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 (provided the
function returns true ). The second option is recording the
shortest paths tree in the 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 vertex or a vertex unreachable from the source). In
addition to these two options, the user can provide her own
custom-made visitor that can take actions at any of the
algorithm's event points.
Parameters
IN: EdgeListGraph& g
A directed or undirected graph whose type must be a model of
Edge List Graph . If a root vertex is
provided, then the graph must also model
Vertex List Graph . Python : The parameter is named graph .
IN: Size N
The number of vertices in the graph. The type Size must
be an integer type. Default: num_vertices(g) . Python : Unsupported parameter.
Named Parameters
IN: weight_map(WeightMap w)
The weight (also know as ``length'' or ``cost'') of each edge in the
graph. The WeightMap type must be a model of Readable Property
Map . The key type for this property map must be the edge
descriptor of the graph. The value type for the weight map must be
Addable with the distance map's value type. Default: get(edge_weight, g) Python : Must be an edge_double_map for the graph. Python default : graph.get_edge_double_map("weight")
OUT: predecessor_map(PredecessorMap p_map)
The predecessor map records the edges in the minimum spanning
tree. Upon completion of the algorithm, the edges (p[u],u)
for all u in V are in the 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 PredecessorMap type
must be a Read/Write
Property Map which key and vertex types the same as the vertex
descriptor type of the graph. Default: dummy_property_map Python : Must be a vertex_vertex_map for the graph.
IN/OUT: distance_map(DistanceMap d)
The shortest path weight from the source vertex to each vertex in
the graph g is recorded in this property map. The type
DistanceMap must be a model of Read/Write
Property Map . The key type of the property map must be the
vertex descriptor type of the graph, and the value type of the
distance map must be Less
Than Comparable . Default: get(vertex_distance,
g) Python : Must be a vertex_double_map for the graph.
IN: root_vertex(Vertex s)
The starting (or "root") vertex from which shortest paths will be
computed. When provided, the distance map need not be initialized
(the algorithm will perform the initialization itself). However, the
graph must model Vertex List
Graph when this parameter is provided. Default: None; if omitted, the user must initialize the
distance map.
IN: visitor(BellmanFordVisitor v)
The visitor object, whose type must be a model of
Bellman-Ford Visitor .
The visitor object is passed by value [1] .
Default: bellman_visitor<null_visitor> Python : The parameter should be an object that derives from
the BellmanFordVisitor type
of the graph.
IN: distance_combine(BinaryFunction combine)
This function object replaces the role of addition in the relaxation
step. The first argument type must match the distance map's value
type and the second argument type must match the weight map's value
type. The result type must be the same as the distance map's value
type. Default: std::plus<D>
with D=typename property_traits<DistanceMap>::value_type . Python : Unsupported parameter.
IN: distance_compare(BinaryPredicate compare)
This function object replaces the role of the less-than operator
that compares distances in the relaxation step. The argument types
must match the distance map's value type. Default: std::less<D>
with D=typename property_traits<DistanceMap>::value_type . Python : Unsupported parameter.
Complexity
The time complexity is O(V E) .
Visitor Event Points vis.examine_edge(e, g) is invoked on every edge in
the graph |V| times.
vis.edge_relaxed(e, g) is invoked when the distance
label for the target vertex is decreased. The edge (u,v) that
participated in the last relaxation for vertex v is an edge in the
shortest paths tree.
vis.edge_not_relaxed(e, g) is invoked if the distance label
for the target vertex is not decreased.
vis.edge_minimized(e, g) is invoked during the
second stage of the algorithm, during the test of whether each edge
was minimized. If the edge is minimized then this function
is invoked.
vis.edge_not_minimized(e, g) is also invoked during the
second stage of the algorithm, during the test of whether each edge
was minimized. If the edge was not minimized, this function is
invoked. This happens when there is a negative cycle in the graph.
Example
An example of using the Bellman-Ford algorithm is in examples/bellman-example.cpp .
Notes
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.
|
| Markdown | # [ Boost C++ Libraries](https://www.boost.org/)
"...one of the most highly regarded and expertly designed C++ library projects in the world." — [Herb Sutter](https://herbsutter.com/) and [Andrei Alexandrescu](http://en.wikipedia.org/wiki/Andrei_Alexandrescu), [C++ Coding Standards](https://books.google.com/books/about/C++_Coding_Standards.html?id=mmjVIC6WolgC)
Search...
This is an older version of Boost and was released in 2016. The [current version](https://www.boost.org/doc/libs/latest/libs/graph/doc/bellman_ford_shortest.html) is 1.90.0.
#  bellman\_ford\_shortest\_paths
```
// named paramter version
template <class EdgeListGraph, class Size, class P, class T, class R>
bool bellman_ford_shortest_paths(const EdgeListGraph& g, Size N,
const bgl_named_params<P, T, R>& params = all defaults);
template <class VertexAndEdgeListGraph, class P, class T, class R>
bool bellman_ford_shortest_paths(const VertexAndEdgeListGraph& g,
const bgl_named_params<P, T, R>& params = all defaults);
// non-named parameter version
template <class EdgeListGraph, class Size, class WeightMap,
class PredecessorMap, class DistanceMap,
class BinaryFunction, class BinaryPredicate,
class BellmanFordVisitor>
bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N,
WeightMap weight, PredecessorMap pred, DistanceMap distance,
BinaryFunction combine, BinaryPredicate compare, BellmanFordVisitor v)
```
The Bellman-Ford algorithm \[[4](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/bibliography.html#bellman58),[11](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/bibliography.html#ford62:_flows),[20](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/bibliography.html#lawler76:_comb_opt),[8](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/bibliography.html#clr90)\] solves the single-source shortest paths problem for a graph with both positive and negative edge weights. For the definition of the shortest paths problem see Section [Shortest-Paths Algorithms](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/graph_theory_review.html#sec:shortest-paths-algorithms). If you only need to solve the shortest paths problem for positive edge weights, Dijkstra's algorithm provides a more efficient alternative. If all the edge weights are all equal to one then breadth-first search provides an even more efficient alternative.
Before calling the bellman\_ford\_shortest\_paths() function, the user must assign the source vertex a distance of zero and all other vertices a distance of infinity *unless* you are providing a starting vertex. The Bellman-Ford algorithm proceeds by looping through all of the edges in the graph, applying the relaxation operation to each edge. In the following pseudo-code, *v* is a vertex adjacent to *u*, *w* maps edges to their weight, and *d* is a distance map that records the length of the shortest path to each vertex seen so far. *p* is a predecessor map which records the parent of each vertex, which will ultimately be the parent in the shortest paths tree
The algorithm repeats this loop *\|V\|* times after which it is guaranteed that the distances to each vertex have been reduced to the minimum possible unless there is a negative cycle in the graph. If there is a negative cycle, then there will be edges in the graph that were not properly minimized. That is, there will be edges *(u,v)* such that *w(u,v) + d\[u\] \< d\[v\]*. The algorithm loops over the edges in the graph one final time to check if all the edges were minimized, returning true if they were and returning false otherwise.
There are two main options for obtaining output from the
bellman\_ford\_shortest\_paths()
function. If the user provides 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 (provided the function returns
true
). The second option is recording the shortest paths tree in the
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 vertex or a vertex unreachable from the source). In addition to these two options, the user can provide her own custom-made visitor that can take actions at any of the algorithm's event points.
### Parameters
IN:
EdgeListGraph& g
> A directed or undirected graph whose type must be a model of [Edge List Graph](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/EdgeListGraph.html). If a root vertex is provided, then the graph must also model [Vertex List Graph](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/VertexListGraph.html).
> **Python**: The parameter is named
>
> graph
>
> .
IN:
Size N
> The number of vertices in the graph. The type
>
> Size
>
> must be an integer type.
> **Default:**
>
> num\_vertices(g)
>
> .
> **Python**: Unsupported parameter.
### Named Parameters
IN:
weight\_map(WeightMap w)
> The weight (also know as \``length'' or \``cost'') of each edge in the graph. The
>
> WeightMap
>
> type must be a model of [Readable Property Map](https://www.boost.org/doc/libs/1_62_0/libs/property_map/doc/ReadablePropertyMap.html). The key type for this property map must be the edge descriptor of the graph. The value type for the weight map must be *Addable* with the distance map's value type.
> **Default:**
>
> get(edge\_weight, g)
>
> **Python**: Must be an
>
> edge\_double\_map
>
> for the graph.
> **Python default**:
>
> graph.get\_edge\_double\_map("weight")
OUT:
predecessor\_map(PredecessorMap p\_map)
> The predecessor map records the edges in the minimum spanning tree. Upon completion of the algorithm, the edges *(p\[u\],u)* for all *u in V* are in the 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
>
> PredecessorMap
>
> type must be a [Read/Write Property Map](https://www.boost.org/doc/libs/1_62_0/libs/property_map/doc/ReadWritePropertyMap.html) which key and vertex types the same as the vertex descriptor type of the graph.
> **Default:**
>
> dummy\_property\_map
>
> **Python**: Must be a
>
> vertex\_vertex\_map
>
> for the graph.
IN/OUT:
distance\_map(DistanceMap d)
> The shortest path weight from the source vertex to each vertex in the graph
>
> g
>
> is recorded in this property map. The type
>
> DistanceMap
>
> must be a model of [Read/Write Property Map](https://www.boost.org/doc/libs/1_62_0/libs/property_map/doc/ReadWritePropertyMap.html). The key type of the property map must be the vertex descriptor type of the graph, and the value type of the distance map must be [Less Than Comparable](http://www.sgi.com/tech/stl/LessThanComparable.html).
> **Default:**
>
> get(vertex\_distance, g)
>
> **Python**: Must be a
>
> vertex\_double\_map
>
> for the graph.
IN:
root\_vertex(Vertex s)
> The starting (or "root") vertex from which shortest paths will be computed. When provided, the distance map need not be initialized (the algorithm will perform the initialization itself). However, the graph must model [Vertex List Graph](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/VertexListGraph.html) when this parameter is provided.
> **Default:** None; if omitted, the user must initialize the distance map.
IN:
visitor(BellmanFordVisitor v)
> The visitor object, whose type must be a model of [Bellman-Ford Visitor](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/BellmanFordVisitor.html). The visitor object is passed by value [\[1\]](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/bellman_ford_shortest.html#1).
> **Default:**
>
> bellman\_visitor\<null\_visitor\>
>
> **Python**: The parameter should be an object that derives from the
>
> [BellmanFordVisitor](https://www.boost.org/doc/libs/1_62_0/libs/graph/doc/BellmanFordVisitor.html#python)
>
> type of the graph.
IN:
distance\_combine(BinaryFunction combine)
> This function object replaces the role of addition in the relaxation step. The first argument type must match the distance map's value type and the second argument type must match the weight map's value type. The result type must be the same as the distance map's value type.
> **Default:**
>
> std::plus\<D\>
>
> with
>
> D=typename property\_traits\<DistanceMap\>::value\_type
>
> .
> **Python**: Unsupported parameter.
IN:
distance\_compare(BinaryPredicate compare)
> This function object replaces the role of the less-than operator that compares distances in the relaxation step. The argument types must match the distance map's value type.
> **Default:**
>
> std::less\<D\>
>
> with
>
> D=typename property\_traits\<DistanceMap\>::value\_type
>
> .
> **Python**: Unsupported parameter.
### Complexity
The time complexity is *O(V E)*.
### Visitor Event Points
- **vis.examine\_edge(e, g)** is invoked on every edge in the graph *\|V\|* times.
- **vis.edge\_relaxed(e, g)** is invoked when the distance label for the target vertex is decreased. The edge *(u,v)* that participated in the last relaxation for vertex *v* is an edge in the shortest paths tree.
- **vis.edge\_not\_relaxed(e, g)** is invoked if the distance label for the target vertex is not decreased.
- **vis.edge\_minimized(e, g)** is invoked during the second stage of the algorithm, during the test of whether each edge was minimized. If the edge is minimized then this function is invoked.
- **vis.edge\_not\_minimized(e, g)** is also invoked during the second stage of the algorithm, during the test of whether each edge was minimized. If the edge was not minimized, this function is invoked. This happens when there is a negative cycle in the graph.
### Example
An example of using the Bellman-Ford algorithm is in [examples/bellman-example.cpp](https://www.boost.org/doc/libs/1_62_0/libs/graph/example/bellman-example.cpp).
### Notes
[\[1\]]() 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.
| | |
|---|---|
| Copyright © 2000 | [Jeremy Siek](http://www.boost.org/people/jeremy_siek.htm), Indiana University ([jsiek@osl.iu.edu](mailto:jsiek@osl.iu.edu)) | |
| Readable Markdown | null |
| Shard | 76 (laksa) |
| Root Hash | 2177253573749532476 |
| Unparsed URL | org,boost!www,/doc/libs/1_62_0/libs/graph/doc/bellman_ford_shortest.html s443 |