Leetcode 305 Number of Islands II
Union Find
// version 2: Union Find
class UnionFind {
private int[] father = null;
private int count;
private int find(int x) {
if (father[x] == x) {
return x;
}
return father[x] = find(father[x]);
}
public UnionFind(int n) {
// initialize your data structure here.
father = new int[n];
for (int i = 0; i < n; ++i) {
father[i] = i;
}
}
public void connect(int a, int b) {
// Write your code here
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b) {
father[root_a] = root_b;
count --;
}
}
public int query() {
return count;
}
public void set_count(int total) {
count = total;
}
}
// version 1: Union Find
class UnionFind{
HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();
UnionFind(int n, int m) {
for (int i = 0 ; i < n; i++) {
for (int j = 0 ; j < m; j++) {
int id = i*m + j;
father.put(id, id);
}
}
}
int compressed_find(int x) {
int parent = father.get(x);
while (parent!=father.get(parent)) {
parent = father.get(parent);
}
int temp = -1;
int fa = 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 = compressed_find(x);
int fa_y = compressed_find(y);
if (fa_x != fa_y)
father.put(fa_x, fa_y);
}
}