- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 70 lines of C++ from the credited upstream file 3235.cpp.
- 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:3 UnionFind(int n) : id(n), rank(n) {4 iota(id.begin(), id.end(), 0);5 }6 7 void unionByRank(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return;12 if (rank[i] < rank[j]) {13 id[i] = j;14 } else if (rank[i] > rank[j]) {15 id[j] = i;16 } else {17 id[i] = j;18 ++rank[j];19 }20 }21 22 int find(int u) {23 return id[u] == u ? u : id[u] = find(id[u]);24 }25 26 private:27 vector<int> id;28 vector<int> rank;29};30 31class Solution {32 public:33 bool canReachCorner(int X, int Y, vector<vector<int>>& circles) {34 const int n = circles.size();35 36 37 UnionFind uf(n + 2);38 39 40 for (int i = 0; i < n; ++i) {41 const int x = circles[i][0];42 const int y = circles[i][1];43 const 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 const int x2 = circles[j][0];55 const int y2 = circles[j][1];56 const int r2 = circles[j][2];57 if (static_cast<long>(x - x2) * (x - x2) +58 static_cast<long>(y - y2) * (y - y2) <=59 static_cast<long>(r + r2) * (r + r2))60 uf.unionByRank(i, j);61 }62 }63 64 65 66 67 return uf.find(n) != uf.find(n + 1);68 }69};70