- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 68 lines of Java from the credited upstream file 3235.java.
- The implementation visibly relies on sequence storage.
- 3 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 UnionFind(int n) {3 id = new int[n];4 rank = new int[n];5 for (int i = 0; i < n; ++i)6 id[i] = i;7 }8 9 public void unionByRank(int u, int v) {10 final int i = find(u);11 final int j = find(v);12 if (i == j)13 return;14 if (rank[i] < rank[j]) {15 id[i] = j;16 } else if (rank[i] > rank[j]) {17 id[j] = i;18 } else {19 id[i] = j;20 ++rank[j];21 }22 }23 24 public int find(int u) {25 return id[u] == u ? u : (id[u] = find(id[u]));26 }27 28 private int[] id;29 private int[] rank;30}31 32class Solution {33 public boolean canReachCorner(int X, int Y, int[][] circles) {34 final int n = circles.length;35 36 37 UnionFind uf = new UnionFind(n + 2);38 39 40 for (int i = 0; i < n; ++i) {41 final int x = circles[i][0];42 final int y = circles[i][1];43 final int r = circles[i][2];44 45 46 if (x - r <= 0 || y + r >= Y)47 uf.unionByRank(i, n);48 49 50 if (x + r >= X || y - r <= 0)51 uf.unionByRank(i, n + 1);52 53 for (int j = 0; j < i; j++) {54 final int x2 = circles[j][0];55 final int y2 = circles[j][1];56 final int r2 = circles[j][2];57 if ((long) (x - x2) * (x - x2) + (long) (y - y2) * (y - y2) <= (long) (r + r2) * (r + r2))58 uf.unionByRank(i, j);59 }60 }61 62 63 64 65 return uf.find(n) != uf.find(n + 1);66 }67}68