Question 2 Number of Island II
Last updated
Last updated
public List<Integer> numIsland2(int m, int n, int[][] positions) {
int[][] graph = new int[m][n];
List<Integer> result = new ArrayList<>();
UF uf = new UF(m * n);
for (int[] position : positions) {
int x = position[0];
int y = position[1];
if (graph[x][y] == 1) {
result.add(uf.count);
continue;
}
graph[x][y] = 1;
uf.count++;
for (int[] dir: dirs) {
int neiX = x + dir[0];
int neiY = y + dir[1];
if (isValid(graph, neiX, neiY) && graph[neiX][neiY] == 1) {
uf.union(x * n + y, neiX* n +neiY);
}
}
return result;
}
}
class UF{
int[] laoda;
int count;
public UF(int n) {
this.laoda = new int[n];
for (int i = 0; i < n; i++) {
laoda[i] = i;
}
this.count = 0; ///注意这个0
}
public void union(int a, int b) {
int alaoda = find(a);
int blaoda = find(b);
if (alaoda != blaoda) {
laoda[alaoda] = blaoda;
count--; //注意这里
}
}
public int find(int a) {
return laoda[a] = laoda[a] == a? a: find(laoda[a]);
}
}