publicclassSolution { public IList<int> NumIslands2(int m, int n, int[][] positions) { UnionFind uf = new UnionFind(m, n); List<int> ans = new List<int>(); foreach (int[] pos in positions) { int r = pos[0], c = pos[1]; ans.Add(uf.Connect(r, c)); } return ans; } }
publicUnionFind(int m, int n) { int len = m * n; size = newint[len]; parents = newint[len]; help = newint[len]; sets = 0; rows = m; cols = n; }
privateintFind(int i) { int hi = 0; while (i != parents[i]) { help[hi++] = i; i = parents[i]; } for (int j = hi - 1; j >= 0; j--) { parents[help[j]] = i; } return i; }
privateintIndex(int r, int c) { return r * cols + c; }
publicintConnect(int r, int c) { int index = Index(r, c); if (size[index] == 0) { parents[index] = index; size[index] = 1; sets++; // Check and union with four neighbors Union(r, c, r - 1, c); Union(r, c, r + 1, c); Union(r, c, r, c - 1); Union(r, c, r, c + 1); } return sets; }
privatevoidUnion(int r1, int c1, int r2, int c2) { if (r1 < 0 || r1 == r || c1 < 0 || c1 == c || r < 0 || r2 == r || c2 < 0 || c2 == c) return; int i1 = Index(r1, c1); int i2 = Index(r2, c2); if (size[i1] == 0 || size[i2] == 0) return; int f1 = Find(i1); int f2 = Find(i2); if (f1 != f2) { if (size[f1] >= size[f2]) { size[f1] += size[f2]; parents[f2] = f1; } else { size[f2] += size[f1]; parents[f1] = f2; } sets--; } } }