Skip to content

GraphDistance ​

The length of a shortest u to v path, respecting edge direction.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageGraphDistance✓
GraphDistance(g, u, v)the number of edges on a shortest u→vu \to v path, or +∞+\infty if vv is unreachable from uu.
Typed signatures
TypePackageApplies
(value, any, any) -> valuecombinatoricsalways

Domain: Collections

Details
  • Weighted (g carries EdgeWeight -> {…}): the SUM of edge weights along the cheapest path (Dijkstra), not an edge count — read numerically, so an exact weight (a fraction, say) comes back as a float, not kept exact. Requires every weight non-negative; a negative one leaves the call unevaluated (see FindShortestPath's own note).

Examples

1 more kept as data, checked against the oracles
Basic #
live ↗
InGraphDistance(PathGraph(5),1,5)\mathrm{GraphDistance}(\mathrm{PathGraph}(5), 1, 5)Out44

No directed path back, so the distance is infinite

live ↗
InGraphDistance(Graph([1,2,3,4],[DirectedEdge(1,2),UndirectedEdge(3,4)]),4,1)\mathrm{GraphDistance}(\mathrm{Graph}(\bigl\lbrack1, 2, 3, 4\bigr\rbrack, \bigl\lbrack\mathrm{DirectedEdge}(1, 2), \mathrm{UndirectedEdge}(3, 4)\bigr\rbrack), 4, 1)Out∞∞

With EdgeWeight given, the distance is the summed weight along the path (5 + 7), not the 2-edge hop count

live ↗
InGraphDistance(Graph([1,2,3],[UndirectedEdge(1,2),UndirectedEdge(2,3)],KeyValuePair⁡(EdgeWeight,[5,7])),1,3)\mathrm{GraphDistance}(\mathrm{Graph}(\bigl\lbrack1, 2, 3\bigr\rbrack, \bigl\lbrack\mathrm{UndirectedEdge}(1, 2), \mathrm{UndirectedEdge}(2, 3)\bigr\rbrack, \operatorname{KeyValuePair}(\mathrm{EdgeWeight}, \bigl\lbrack5, 7\bigr\rbrack)), 1, 3)Out1212
About
Examples4
Checked againstWolfram Language 3 agree
CrosswalkWolfram Language

See also: FindShortestPath, GraphDistanceMatrix, WeightedAdjacencyMatrix, ConnectedComponents