- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 101 lines of Java from the credited upstream file 803.java.
- The implementation visibly relies on sequence storage.
- 6 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 sz = new int[n];5 for (int i = 0; i < n; ++i)6 id[i] = i;7 Arrays.fill(sz, 1);8 }9 10 public void unionBySize(int u, int v) {11 final int i = find(u);12 final int j = find(v);13 if (i == j)14 return;15 if (sz[i] < sz[j]) {16 sz[j] += sz[i];17 id[i] = j;18 } else {19 sz[i] += sz[j];20 id[j] = i;21 }22 }23 24 public int getStableSize() {25 26 return sz[find(0)];27 }28 29 private int[] id;30 private int[] sz;31 32 private int find(int u) {33 return id[u] == u ? u : (id[u] = find(id[u]));34 }35}36class Solution {37 public int[] hitBricks(int[][] grid, int[][] hits) {38 this.m = grid.length;39 this.n = grid[0].length;40 41 UnionFind uf = new UnionFind(m * n + 1); 42 43 44 for (int[] hit : hits) {45 final int i = hit[0];46 final 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 int[] ans = new int[hits.length];58 int stableSize = uf.getStableSize();59 60 for (int i = hits.length - 1; i >= 0; --i) {61 final int x = hits[i][0];62 final int y = hits[i][1];63 if (grid[x][y] == 2) { 64 grid[x][y] = 1; 65 unionNeighbors(grid, uf, x, y);66 final 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 int m;77 private int n;78 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};79 80 private void unionNeighbors(int[][] grid, UnionFind uf, int i, int j) {81 final int hash = getHash(i, j);82 83 for (int[] dir : DIRS) {84 final int x = i + dir[0];85 final int y = j + dir[1];86 if (x < 0 || x == m || y < 0 || y == n)87 continue;88 if (grid[x][y] != 1)89 continue;90 uf.unionBySize(hash, getHash(x, y));91 }92 93 if (i == 0)94 uf.unionBySize(hash, 0);95 }96 97 private int getHash(int i, int j) {98 return i * n + j + 1;99 }100}101