- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 51 lines of C++ from the credited upstream file 547.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) : count(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 --count;21 }22 23 int getCount() const {24 return count;25 }26 27 private:28 int count;29 vector<int> id;30 vector<int> rank;31 32 int find(int u) {33 return id[u] == u ? u : id[u] = find(id[u]);34 }35};36 37class Solution {38 public:39 int findCircleNum(vector<vector<int>>& isConnected) {40 const int n = isConnected.size();41 UnionFind uf(n);42 43 for (int i = 0; i < n; ++i)44 for (int j = i; j < n; ++j)45 if (isConnected[i][j] == 1)46 uf.unionByRank(i, j);47 48 return uf.getCount();49 }50};51