Search code examples
algorithmgraph-algorithmdepth-first-searchminimum-spanning-treekruskals-algorithm

Storing Path information in Kruskal's Algorithm


I have generated a minimum spanning tree using Kruskal's algorithm and I wanted to know how to store paths

This is my minimum spanning tree

Loc1 |  Loc2 |  Distance
  02 |   10  |    2.00 Km
  05 |   07  |    5.39 Km
  02 |   09  |    5.83 Km
  04 |   05  |    5.83 Km
  06 |   08  |    5.83 Km
  03 |   09  |    7.07 Km
  01 |   04  |    11.18 Km
  07 |   09  |    11.18 Km
  07 |   08  |    15.81 Km
Total Weight = 70.12 Km
----------------------------------------------------

Solution

  • It depends on how much extra space you have. Assume you need to be space-efficient:

    1. Orient the edges in such a way that the resulting structure has at most one parent node for each node. How to do it? Just pick a node and make it the root. It's children are first level nodes etc
    2. Now store the resulting graph in the format child->parent (In your table you can make Loc1 column child and Loc2 column parent. Index it by child)
    3. For given two nodes, a and y, whose distance needs to be calculated, find their parental sets and see where they intersect. Ex. If parent of x is A, A's parent is B... the parental path is ABCDLMN (where N is the root). Similarly if the parental root for y is EFLMN. As you can see, the lowest common root for both of them is L. Distance from x->L is 5, y->L is 3, => distance between x and y is 5+3=8.

    Complexity: O(hlogn) where h is the height of the tree and n is the number of elements in the tree (I am assuming lookup time for each node in logn).