Union-Find Algorithm
Union-Find Algrithm is used to check whether two components are connected or not.
Examples:
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:
So, how to implement it?
How is the time complexity of the operations?
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:
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.)
Time complexity:
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.
The benefit of doing this can decrease the height of the tree.
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:
So, this approach can also decrease the height of the tree.
Reference:https://www.cs.duke.edu/courses/cps100e/fall09/notes/UnionFind.pdf (普林斯顿的这位老爷爷讲得真的很清楚,youtube上可以收到他的视频。)