0

Hello I'm trying to figure out how to calculate the average distance between two nodes in a weighted undirected graph. Furthermore, this graph is a tree so it has V - 1 edges.

I thought about using Floyd Warshall to compute all-shortest paths and then calculate the average. But that would turn out to be in O(E^3) time complexity. And it really isn't enough.

I've also been thinking of using Dynamic Programming to solve it but I can't really see how... Can anyone give me a few pointers please? I don't want a direct answer, just a few tips so that I can keep thinking about it :)

Noé Weeks
  • 35
  • 6

1 Answers1

0

Build and maintain a table of all shortest paths (no surprise). Each entry includes the lowest-known cost and the path.

Start the table by filling in all the edges (only paths of length 1); the other entries are inf.

Iterate through the table, considering two cases: add a node on the left, and add a node on the right. At each end, consider only the nodes reachable by a single edge from the end node. Is that path shorter than the existing entry?

For instance, assume we have an edge between nodes I and J; call it IJ, we also have edge JK. Is the cost of IJ + JK less than the current entry for edge IK? If so, replace it and record the path IJK; if not, go to the next edge/node/path.

You can iterate through all existing paths until there are no updates. Perhaps better, index the paths in which each shortest path is used; that allows you to update all paths whenever a particular sub-path is improved.

Continue the process until you make a full pass over the graph with no updates. If you maintain that sub-path index, I think you can do this in a only one or two passes over the graph. I believe that this would make the process O(E*N^2) (on edges and nodes).

Prune
  • 76,765
  • 14
  • 60
  • 81