public IList <int> NumIslands2(int rows, int cols, int[,] positions) { var dsu = new DSU(rows * cols); var result = new List <int>(); int GetIndx(int r, int c) => r * cols + c; for (var i = 0; i < positions.GetLength(0); i++) { var r = positions[i, 0]; var c = positions[i, 1]; var indx = GetIndx(r, c); dsu.Set(indx); var up = GetIndx(r - 1, c); if (r - 1 >= 0 && dsu.IsSet(up)) { dsu.Union(indx, up); } var down = GetIndx(r + 1, c); if (r + 1 < rows && dsu.IsSet(down)) { dsu.Union(indx, down); } var left = GetIndx(r, c - 1); if (c - 1 >= 0 && dsu.IsSet(left)) { dsu.Union(indx, left); } var right = GetIndx(r, c + 1); if (c + 1 < cols && dsu.IsSet(right)) { dsu.Union(indx, right); } result.Add(dsu.GetCount()); } return(result); }