题目地址:
https://leetcode.com/problems/number-of-islands-ii/
给定一个二维零矩阵,再给点一个数组,数组每个位置是个长为 2 2 2的整数数组,是矩阵里的一个坐标。遍历数组的同时,会把矩阵相应坐标位置上的 0 0 0变为 1 1 1。要求在线计算遍历数组的时候连通块(岛屿)的数量。
思路是并查集。在遍历数组的时候,取出坐标,如果矩阵在该位置已经有岛屿则略过(这里主要是预防数组里有重复坐标,也就是同一个位置变了两次 1 1 1);如果没有岛屿,则先将岛屿数加 1 1 1,然后将这个岛屿和四周的岛屿全做一遍union,每union一次就要将岛屿数减去 1 1 1,同时动态将岛屿数加入最后答案即可。代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
class UnionFind {
private int[] parent, rank;
private int count;
public UnionFind(int size) {
parent = new int[size];
rank = new int[size];
// 先标记为-1,表示这个位置没有陆地
Arrays.fill(parent, -1);
Arrays.fill(rank, 1);
}
public int find(int p) {
if (p != parent[p]) {
parent[p] = find(parent[p]);
}
return parent[p];
}
public void union(int p, int q) {
// 如果有一个不是陆地,则不用union
if (parent[p] == -1 || parent[q] == -1) {
return;
}
int pRoot = find(p), qRoot = find(q);
if (pRoot == qRoot) {
return;
}
if (rank[pRoot] < rank[qRoot]) {
parent[pRoot] = qRoot;
} else if (rank[pRoot] > rank[qRoot]) {
parent[qRoot] = pRoot;
} else {
parent[pRoot] = qRoot;
rank[qRoot]++;
}
// 每union一次,就要将岛屿数量减去1
count--;
}
public int getCount() {
return count;
}
private void add(int x, int y, int m, int n) {
int pos = mapToInt(x, y, n);
// 已经是陆地了,就不用重复变为陆地了
if (parent[pos] != -1) {
return;
}
// 先变为陆地
parent[pos] = pos;
// 先假设这个陆地构成了一个新的连通块,将岛屿数加1,后面union的时候再减
count++;
// 四个方向上做union
if (x + 1 < m) {
union(mapToInt(x, y, n), mapToInt(x + 1, y, n));
}
if (x - 1 >= 0) {
union(mapToInt(x, y, n), mapToInt(x - 1, y, n));
}
if (y + 1 < n) {
union(mapToInt(x, y, n), mapToInt(x, y + 1, n));
}
if (y - 1 >= 0) {
union(mapToInt(x, y, n), mapToInt(x, y - 1, n));
}
}
private int mapToInt(int x, int y, int n) {
return x * n + y;
}
}
public List<Integer> numIslands2(int m, int n, int[][] positions) {
List<Integer> res = new ArrayList<>();
UnionFind uf = new UnionFind(m * n);
for (int i = 0; i < positions.length; i++) {
int x = positions[i][0], y = positions[i][1];
uf.add(x, y, m, n);
res.add(uf.getCount());
}
return res;
}
}
时间复杂度 O ( k log ∗ k ) O(k\log ^*k) O(klog∗k)( log ∗ \log^* log∗是iterative logarithm, k k k是positions的长度),空间复杂度 O ( m n ) O(mn) O(mn)。