Union-find over cells
Time O(k α(mn)) Space O(mn)parent[r × n + c] = −1 for water. Adding land creates its own set; union with land neighbours; record the count.
import java.util.*;
class Solution {
private int[] parent;
public List<Integer> numIslands2(int m, int n, int[][] positions) {
parent = new int[m * n];
Arrays.fill(parent, -1);
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
List<Integer> out = new ArrayList<>();
int count = 0;
for (int[] p : positions) {
int id = p[0] * n + p[1];
if (parent[id] == -1) {
parent[id] = id;
count++;
for (int[] d : dirs) {
int r = p[0] + d[0], c = p[1] + d[1];
if (r < 0 || c < 0 || r >= m || c >= n || parent[r * n + c] == -1) continue;
int a = find(id), b = find(r * n + c);
if (a != b) { parent[a] = b; count--; }
}
}
out.add(count);
}
return out;
}
private int find(int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
}
}Verdict: BFS after each addition would be O(k × mn).