Find the Weak Connected Component in the Directed Graph
DAG
public class Solution {
/**
* @param nodes a array of Directed graph node
* @return a connected set of a directed graph
*/
class UnionFind{
HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();
UnionFind(HashSet<Integer> hashSet){
for(Integer now : hashSet) {
father.put(now, now);
}
}
int find(int x){
int parent = father.get(x);
while(parent!=father.get(parent)) {
parent = father.get(parent);
}
return parent;
}
int compressed_find(int x){
int parent = father.get(x);
while(parent!=father.get(parent)) {
parent = father.get(parent);
}
int temp = -1;
int fa = father.get(x);
while(fa!=father.get(fa)) {
temp = father.get(fa);
father.put(fa, parent) ;
fa = temp;
}
return parent;
}
void union(int x, int y){
int fa_x = find(x);
int fa_y = find(y);
if(fa_x != fa_y)
father.put(fa_x, fa_y);
}
}
List<List<Integer> > print(HashSet<Integer> hashSet, UnionFind uf) {
List<List <Integer> > ans = new ArrayList<List<Integer>>();
HashMap<Integer, List <Integer>> hashMap = new HashMap<Integer, List <Integer>>();
for(int i : hashSet){
int fa = uf.compressed_find(i);
if(!hashMap.containsKey(fa)) {
hashMap.put(fa, new ArrayList<Integer>() );
}
//List <Integer> now = hashMap.get(fa);
hashMap.get(fa).add(i);
// hashMap.put(fa, now);
}
for( List <Integer> now: hashMap.values()) {
Collections.sort(now);
ans.add(now);
}
return ans;
}
List<List<Integer> > print1( UnionFind uf) {
List<List <Integer> > ans = new ArrayList<List<Integer>>();
HashMap<Integer, List <Integer>> hashMap = new HashMap<Integer, List <Integer>>();
for(int i : uf.father.keySet()){
int fa = uf.compressed_find(i);
if(!hashMap.containsKey(fa)) {
hashMap.put(fa, new ArrayList<Integer>() );
}
//List <Integer> now = hashMap.get(fa);
hashMap.get(fa).add(i);
// hashMap.put(fa, now);
}
for( List <Integer> now: hashMap.values()) {
Collections.sort(now);
ans.add(now);
}
return ans;
}
public List<List<Integer>> connectedSet2(ArrayList<DirectedGraphNode> nodes){
// Write your code here
HashSet<Integer> hashSet = new HashSet<Integer>();
for(DirectedGraphNode now : nodes){
hashSet.add(now.label);
for(DirectedGraphNode neighbour : now.neighbors) {
hashSet.add(neighbour.label);
}
}
UnionFind uf = new UnionFind(hashSet);
for(DirectedGraphNode now : nodes){
for(DirectedGraphNode neighbour : now.neighbors) {
int fnow = uf.compressed_find(now.label);
int fneighbour = uf.compressed_find(neighbour.label);
if(fnow!=fneighbour) {
uf.union(now.label, neighbour.label);
}
}
}
return print1(uf);
//return print(hashSet, uf);
}
}