- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 103 lines of C++ from the credited upstream file 803.cpp.
- The implementation visibly relies on sequence storage.
- 5 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), sz(n, 1) {4 iota(id.begin(), id.end(), 0);5 }6 7 void unionBySize(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return;12 if (sz[i] < sz[j]) {13 sz[j] += sz[i];14 id[i] = j;15 } else {16 sz[i] += sz[j];17 id[j] = i;18 }19 }20 21 int getStableSize() {22 23 return sz[find(0)];24 }25 26 private:27 vector<int> id;28 vector<int> sz;29 30 int find(int u) {31 return id[u] == u ? u : id[u] = find(id[u]);32 }33};34 35class Solution {36 public:37 vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {38 m = grid.size();39 n = grid[0].size();40 41 UnionFind uf(m * n + 1); 42 43 44 for (const vector<int>& hit : hits) {45 const int i = hit[0];46 const int j = hit[1];47 if (grid[i][j] == 1)48 grid[i][j] = 2;49 }50 51 52 for (int i = 0; i < m; ++i)53 for (int j = 0; j < n; ++j)54 if (grid[i][j] == 1)55 unionNeighbors(grid, uf, i, j);56 57 vector<int> ans(hits.size());58 int stableSize = uf.getStableSize();59 60 for (int i = hits.size() - 1; i >= 0; --i) {61 const int x = hits[i][0];62 const int y = hits[i][1];63 if (grid[x][y] == 2) { 64 grid[x][y] = 1; 65 unionNeighbors(grid, uf, x, y);66 const int newStableSize = uf.getStableSize();67 if (newStableSize > stableSize)68 ans[i] = newStableSize - stableSize - 1; 69 stableSize = newStableSize;70 }71 }72 73 return ans;74 }75 76 private:77 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};78 int m;79 int n;80 81 void unionNeighbors(const vector<vector<int>>& grid, UnionFind& uf, int i,82 int j) {83 const int hash = getHash(i, j);84 85 for (const auto& [dx, dy] : kDirs) {86 const int x = i + dx;87 const int y = j + dy;88 if (x < 0 || x == m || y < 0 || y == n)89 continue;90 if (grid[x][y] != 1)91 continue;92 uf.unionBySize(hash, getHash(x, y));93 }94 95 if (i == 0)96 uf.unionBySize(hash, 0);97 }98 99 int getHash(int i, int j) {100 return i * n + j + 1;101 }102};103