标签:
主要是看了这篇文章
http://www.geeksforgeeks.org/union-find/
总结下目前理解的Union-Find
用在disjoint-set data structure上,disjoint-set keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets.
Union-Find is an algorithm that performs two useful operations on such a data structure:
1. Find
determine which subset a particular element is in, this can be used to determin whether two elements are in the same subset
2. Union
join two subsets into a single one
Union-Find can be used to check whether an undirected graph contains cycle or not, and this algorithm assumes that graph doesn‘t contain any self-loops
say we have a graph as below:
[0, 1]
[1, 2]
[2, 0]
When using union-find to process the graph, we use a hashmap to store the parent-child relationship.
1) first we have node 0 and node 1
the map doesn‘t contain 0 nor 1, so it returns 0 and 1 themselves (because they are the parent of themselves by now)
And we connect them together by making 0 the parent of 1 or 1 the parent of 0
so put (0->1) in the map
2) and then we have node 1 and node 2
the map doesn‘t contain 1 nor 2 so it returns 1 for node 1 and returns 2 for node 2
And we connect them together by putting (1->2) in the map
now we have (0->1), (1->2) in the map
3) For node 2 and node 0
the parent of node 2 is 2 itself, but the parent of node 0 is also 2, they equal to each other meaning that they belong to the same subset
Therefore, we found a cycle
In the code, I use an array instead of a hashmap, and fill the array with -1 at first meaning that this is the end, this number is the parent of itself
public boolean validTree(int n, int[][] edges) { if(edges == null) return false; int[] parent = new int[n]; Arrays.fill(parent, -1); for(int i = 0; i < edges.length; i++){ int x = find(parent, edges[i][0]); int y = find(parent, edges[i][1]); if(x==y) return false; parent[x] = y; } return edges.length == n-1; } private int find(int[] parent, int i){ if(parent[i] == -1) return i; return find(parent, parent[i]); }
也可以用在另外两道lintcode题目上
Find the Weak Connected Component in the Directed Graph
Find the Connected Component in the Undirected Graph
代码类似,总的来说union-find就是在disjoint-set 的题目上面很有帮助
标签:
原文地址:http://www.cnblogs.com/momoco/p/4845413.html