-1

I want to get distance of all nodes from all other nodes. For example, if I have 4 nodes then i want distance of path

(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)

i.e. all pairs that are possible

Note: Every node does have a path from every other node.

My approach : I thought of applying Dijkstra's algorithm but it works for a single source and then I have to apply it for every node as source and then take out unique pairs from them which would have very high complexity.

Edit : What would be the case if I have a minimum spanning Tree and have to perform the same task? I mean there is just one path from one node to other.

Karan Nagpal
  • 51
  • 2
  • 8
  • 1
    Please include your `node` data structure, as well as the code for what you have tried so far. – brianpck Nov 04 '16 at 19:41
  • I am taking reference of the code given here. http://www.geeksforgeeks.org/greedy-algorithms-set-7-dijkstras-algorithm-for-adjacency-list-representation/ and just running it the dijkstra function for all possible nodes. – Karan Nagpal Nov 04 '16 at 19:44
  • 1
    [Floyd–Warshall algorithm](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm) – Sergey Kalinichenko Nov 04 '16 at 19:45
  • no other algorithm with less complexity? O(n^3) will be too slow if I have lets say 10^5 nodes. – Karan Nagpal Nov 04 '16 at 19:48
  • @KaranNagpal Repeated application of Dijkstra's algorithm or A* will usually be faster. Note that you are asking for O(n²) outputs, so with 10^5 nodes any algorithm will take a long time. – Sven Marnach Nov 04 '16 at 19:50
  • I have edited the question and added one more possible query I have. – Karan Nagpal Nov 04 '16 at 19:58

1 Answers1

2

You can try with Floyd–Warshall algorithm.
Time complexity is O(V^3) where V is the number of nodes.

Pseudo-code from Wikipedia:

1 let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity)
2 for each vertex v
3    dist[v][v] ← 0
4 for each edge (u,v)
5    dist[u][v] ← w(u,v)  // the weight of the edge (u,v)
6 for k from 1 to |V|
7    for i from 1 to |V|
8       for j from 1 to |V|
9          if dist[i][j] > dist[i][k] + dist[k][j] 
10             dist[i][j] ← dist[i][k] + dist[k][j]
11         end if

If you are working with trees, just make a BFS for each node. This take O(V*(V+E)), that actually is O(V^2) since E = V-1 in trees.

Since the output (all pairs distance) size is V*(V-1), this can't be done in less than O(V^2).

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53