给定 n, m, 分别代表一个二维矩阵的行数和列数, 并给定一个大小为 k 的二元数组A. 初始二维矩阵全0. 二元数组A内的k个元素代表k次操作, 设第i个元素为 (A[i].x, A[i].y), 表示把二维矩阵中下标为A[i].x行A[i].y列的元素由海洋变为岛屿. 问在每次操作之后, 二维矩阵中岛屿的数量. 你需要返回一个大小为k的数组.
并查集
把每个陆地看作一个集合 当新添加的元素上下左右有陆地并且它们不在一个集合 把它们合并为一个集合
每新创建一个陆地 至多会增加一个岛屿 每遇到一个不在同一集合的陆地 岛屿数量就会减1
public class Solution {
/**
* @param n: An integer
* @param m: An integer
* @param operators: an array of point
* @return: an integer array
*/
private int[] father = null;
private int[] isLand = null;
int count = 0;
public int find(int a){
if(father[a] == a)
return a;
return father[a] = find(father[a]);
}
public List<Integer> numIslands2(int n, int m, Point[] operators) {
List<Integer> list = new ArrayList<>();
if(n == 0 || m == 0 || operators == null)
return list;
int[] cx = {1, 0, -1, 0};
int[] cy = {0, 1, 0, -1};
father = new int[n * m];
isLand = new int[n * m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
father[i * m + j] = i * m + j;
isLand[i * m + j] = 0;
}
}
for(Point point : operators){
int pos = point.x * m + point.y;
if(isLand[pos] == 1){
list.add(count);
continue;
}
isLand[pos] = 1;
count++;
for(int i = 0; i < 4; i++){
int newx = point.x + cx[i];
int newy = point.y + cy[i];
int newpos = newx * m + newy;
if(newx >= 0 && newy >= 0 && newx < n && newy < m && isLand[newpos] == 1){
if(find(newpos) != find(pos)){
father[find(newpos)] = pos;
count--;
}
}
}
list.add(count);
}
return list;
}
}