Union-Find Algorithm

时间:2023-03-09 07:23:01
Union-Find Algorithm

Union-Find Algrithm is used to check whether two components are connected or not.

Examples:

Union-Find Algorithm

By using the graph, we can easily find whether two components are connected or not, if there is no such graph, how do we know whether two components are connected or not?

Answer: For all connected components, we set their "root" to be the same.

So, we use an array to record the root of each component, if their roots are the same, return true, otherwise, return false.

Example:

Union-Find Algorithm

Union-Find Algorithm

Union-Find Algorithm

Union-Find Algorithm

So, how to implement it?

Union-Find Algorithm

How is the time complexity of the operations?

Union-Find Algorithm

So, Union operation is kind of expensive, can we decrease it?

Yes, instead of making all the components use the same root id, we can just set the parent id of root component in one set to the root id of another set. (Why we cannot just set the parent id of the root component in one set to the id of the connected component in another set???)

Example:

Union-Find Algorithm

Union-Find Algorithm

But the problem is when we check whether two components have the same root, the worst case time complexity is O(n). n refers to the size of the components, and this happens when we have a thin tree (all components are in the same tree, but this tree has no branches.)

Union-Find Algorithm

Time complexity:

Union-Find Algorithm

So, the approach above cannot decrease the union operation time complexity, rather, it increases the find operation time complexity.

If we have a closer look, we can find the reason why quick-union approach is not performing well is because the height of the tree could be very tall. So, the question becomes how to decrease the height of th tree?

There are two approaches:

First, when we marge two trees, the root of the smaller tree (with less # of components) will be connected to the root of larger tree.

Union-Find Algorithm

Union-Find Algorithm

The benefit of doing this can decrease the height of the tree.

Union-Find Algorithm

Union-Find Algorithm

Another approach is called path compression. The idea is every time when we get the root of a component, we always set its parent id to the root id.

Example:

Union-Find Algorithm

Union-Find Algorithm

Union-Find Algorithm

So, this approach can also decrease the height of the tree.

Reference:https://www.cs.duke.edu/courses/cps100e/fall09/notes/UnionFind.pdf (普林斯顿的这位老爷爷讲得真的很清楚,youtube上可以收到他的视频。)