Skip to content

GraphDistanceMatrix ​

All-pairs shortest-path distances of a Graph, as a matrix.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageGraphDistanceMatrix✓
GraphDistanceMatrix(g)row/column order follows VertexList(g); entry (i, j) is GraphDistance(g, v_i, v_j).
Typed signatures
TypePackageApplies
(value) -> list<list<real | signed_infinity>>combinatoricsalways

Domain: Collections

Details
  • Respects edge direction, same as GraphDistance itself -- row i is the distances FROM vertex i.
  • An unreachable pair reads PositiveInfinity, matching GraphDistance on a disconnected graph.
  • Weighted (g carries EdgeWeight): every entry is GraphDistance's own weighted (Dijkstra, summed-weight) reading, not an edge count; a negative weight leaves the WHOLE matrix unevaluated, same as GraphDistance itself.

Examples

Basic #
live ↗
InGraphDistanceMatrix(CycleGraph(3))\mathrm{GraphDistanceMatrix}(\mathrm{CycleGraph}(3))Out[[0,1,1],[1,0,1],[1,1,0]]\bigl\lbrack\bigl\lbrack0, 1, 1\bigr\rbrack, \bigl\lbrack1, 0, 1\bigr\rbrack, \bigl\lbrack1, 1, 0\bigr\rbrack\bigr\rbrack
live ↗
InGraphDistanceMatrix(Graph([1,2,3,4],[UndirectedEdge(1,2),UndirectedEdge(3,4)]))\mathrm{GraphDistanceMatrix}(\mathrm{Graph}(\bigl\lbrack1, 2, 3, 4\bigr\rbrack, \bigl\lbrack\mathrm{UndirectedEdge}(1, 2), \mathrm{UndirectedEdge}(3, 4)\bigr\rbrack))Out[[0,1,∞,∞],[1,0,∞,∞],[∞,∞,0,1],[∞,∞,1,0]]\bigl\lbrack\bigl\lbrack0, 1, ∞, ∞\bigr\rbrack, \bigl\lbrack1, 0, ∞, ∞\bigr\rbrack, \bigl\lbrack∞, ∞, 0, 1\bigr\rbrack, \bigl\lbrack∞, ∞, 1, 0\bigr\rbrack\bigr\rbrack

With EdgeWeight given, entry (1, 3) is the summed weight 5 + 7, not the 2-edge hop count

live ↗
InGraphDistanceMatrix(Graph([1,2,3],[UndirectedEdge(1,2),UndirectedEdge(2,3)],KeyValuePair⁡(EdgeWeight,[5,7])))\mathrm{GraphDistanceMatrix}(\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)))Out[[0,5,12],[5,0,7],[12,7,0]]\bigl\lbrack\bigl\lbrack0, 5, 12\bigr\rbrack, \bigl\lbrack5, 0, 7\bigr\rbrack, \bigl\lbrack12, 7, 0\bigr\rbrack\bigr\rbrack
About
Examples3
Checked againstWolfram Language 3 agree
CrosswalkWolfram Language

See also: GraphDistance, FindShortestPath, WeightedAdjacencyMatrix, VertexEccentricity