TransWikia.com

Sum of a path on a graph

Mathematica Asked by Wombles on October 20, 2020

I need to take my graph:

g = Graph[{A [UndirectedEdge] B, B [UndirectedEdge] C, 
   C [UndirectedEdge] A, C [UndirectedEdge] D, 
   A [UndirectedEdge] D, B [UndirectedEdge] D}, 
  EdgeWeight -> {14, 46, 49, 48, 38, 16}, EdgeLabels -> "EdgeWeight", 
  VertexLabels -> "Name"]

and Find the sum of the weights along an arbitrary path, for example A->B->C->-D->A
I’ve been trying to use GraphDistance but that only lets me go a single step. Does anyone know how to specify a path instead of just two vertices?

One Answer

Total[GraphDistance[g, #[[1]], #[[2]]] & /@ 
  Partition[{A, B, C, D, A}, 2, 1]]

Partition[{A, B, C, D, A}, 2, 1]

gives the list of individual path segments.

GraphDistance

calculates all the lengths of these individual segments.

Total 

adds them up.

Correct answer by David G. Stork on October 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP