dim4o

FindRoot with path compression

Oct 28th, 2015
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.54 KB | None | 0 0
  1.         private static int FindRoot(int node, int[] parent)
  2.         {
  3.             // Find the root parent for the node
  4.             int root = node;
  5.             while (parent[root] != root)
  6.             {
  7.                 root = parent[root];
  8.             }
  9.  
  10.             // Optimize(compress) path from ndoe to root
  11.             while (node != root)
  12.             {
  13.                 var oldParentNode = parent[node];
  14.                 parent[node] = root;
  15.                 node = oldParentNode;
  16.             }
  17.             return root;
  18.         }
Advertisement
Add Comment
Please, Sign In to add comment