- 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 C++ from the credited upstream file 305.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 vector<int> id;4 5 UnionFind(int n) : id(n, -1), rank(n) {}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> rank;28};29 30class Solution {31 public:32 vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {33 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};34 vector<int> ans;35 vector<vector<bool>> seen(m, vector<bool>(n));36 UnionFind uf(m * n);37 int count = 0;38 39 for (const vector<int>& p : positions) {40 const int i = p[0];41 const int j = p[1];42 if (seen[i][j]) {43 ans.push_back(count);44 continue;45 }46 seen[i][j] = true;47 const int id = getId(i, j, n);48 uf.id[id] = id;49 ++count;50 for (const auto& [dx, dy] : kDirs) {51 const int x = i + dx;52 const int y = j + dy;53 if (x < 0 || x == m || y < 0 || y == n)54 continue;55 const int neighborId = getId(x, y, n);56 if (uf.id[neighborId] == -1) 57 continue;58 const int currentRoot = uf.find(id);59 const int neighborRoot = uf.find(neighborId);60 if (currentRoot != neighborRoot) {61 uf.unionByRank(currentRoot, neighborRoot);62 --count;63 }64 }65 ans.push_back(count);66 }67 68 return ans;69 }70 71 private:72 int getId(int i, int j, int n) {73 return i * n + j;74 }75};76