- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 76 lines of Java from the credited upstream file 305.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public int[] id;3 4 public UnionFind(int n) {5 id = new int[n];6 rank = new int[n];7 Arrays.fill(id, -1); 8 }9 10 public void unionByRank(int u, int v) {11 final int i = find(u);12 final int j = find(v);13 if (i == j)14 return;15 if (rank[i] < rank[j]) {16 id[i] = j;17 } else if (rank[i] > rank[j]) {18 id[j] = i;19 } else {20 id[i] = j;21 ++rank[j];22 }23 }24 25 public int find(int u) {26 return id[u] == u ? u : (id[u] = find(id[u]));27 }28 29 private int[] rank;30}31 32class Solution {33 public List<Integer> numIslands2(int m, int n, int[][] positions) {34 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};35 List<Integer> ans = new ArrayList<>();36 boolean[][] seen = new boolean[m][n];37 UnionFind uf = new UnionFind(m * n);38 int count = 0;39 40 for (int[] p : positions) {41 final int i = p[0];42 final int j = p[1];43 if (seen[i][j]) {44 ans.add(count);45 continue;46 }47 seen[i][j] = true;48 final int id = getId(i, j, n);49 uf.id[id] = id;50 ++count;51 for (int[] dir : DIRS) {52 final int x = i + dir[0];53 final int y = j + dir[1];54 if (x < 0 || x == m || y < 0 || y == n)55 continue;56 final int neighborId = getId(x, y, n);57 if (uf.id[neighborId] == -1) 58 continue;59 final int currentParent = uf.find(id);60 final int neighborParent = uf.find(neighborId);61 if (currentParent != neighborParent) {62 uf.unionByRank(currentParent, neighborParent);63 --count;64 }65 }66 ans.add(count);67 }68 69 return ans;70 }71 72 private int getId(int i, int j, int n) {73 return i * n + j;74 }75}76