shortest_path#
- graph_tool.topology.shortest_path(g, source, target, weights=None, negative_weights=False, pred_map=None, dag=False)[source]#
Return the shortest path from
source
totarget
.- Parameters:
- g
Graph
Graph to be used.
- source
Vertex
Source vertex of the search.
- target
Vertex
Target vertex of the search.
- weights
EdgePropertyMap
(optional, default:None
) The edge weights.
- negative_weights
bool
(optional, default:False
) If
True
, this will trigger the use of the Bellman-Ford algorithm.- pred_map
VertexPropertyMap
(optional, default:None
) Vertex property map with the predecessors in the search tree. If this is provided, the shortest paths are not computed, and are obtained directly from this map.
- dag
bool
(optional, default:False
) If
True
, assume that the graph is a Directed Acyclic Graph (DAG), which will be faster ifweights
are given, in which case they are also allowed to contain negative values (irrespective of the parameternegative_weights
).
- g
- Returns:
Notes
The paths are computed with a breadth-first search (BFS) or Dijkstra’s algorithm [dijkstra], if weights are given. If
negative_weights == True
, the Bellman-Ford algorithm is used [bellman-ford], which accepts negative weights, as long as there are no negative loops.The algorithm runs in \(O(V + E)\) time, or \(O(V \log V)\) if weights are given (if
dag == True
this improves to \(O(V+E)\)).References
[bfs]Edward Moore, “The shortest path through a maze”, International Symposium on the Theory of Switching (1959), Harvard University Press
[dijkstra]E. Dijkstra, “A note on two problems in connexion with graphs.” Numerische Mathematik, 1:269-271, 1959.
[dijkstra-boost]http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
Examples
>>> from numpy.random import poisson >>> g = gt.random_graph(300, lambda: (poisson(4), poisson(4))) >>> vlist, elist = gt.shortest_path(g, g.vertex(10), g.vertex(11)) >>> print([str(v) for v in vlist]) ['10', '114', '96', '97', '11'] >>> print([str(e) for e in elist]) ['(10, 114)', '(114, 96)', '(96, 97)', '(97, 11)']