A 2d grid map of m
rows and n
columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example:
Given m = 3, n = 3
, positions = [[0,0], [0,1], [1,2], [2,1]]
.
Initially, the 2d grid grid
is filled with water. (Assume 0 represents water and 1 represents land).
0 0 0 0 0 0 0 0 0
Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.
1 0 0 0 0 0 Number of islands = 1 0 0 0
Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
1 1 0 0 0 0 Number of islands = 1 0 0 0
Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
1 1 0 0 0 1 Number of islands = 2 0 0 0
Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
1 1 0 0 0 1 Number of islands = 3 0 1 0
We return the result as an array: [1, 1, 2, 3]
用一个一维数组来表示 matrix
定义四个方向,依次检查四个方向
用find 函数来辨别 是否被 union 过
int[][] dirs = new int[][] {{1,0}, {-1, 0}, {0, 1}, {0,-1}};
public List<Integer> numIslands2(int m, int n, int[][] positions) {
int[] roots = new int[m * n];
List<Integer> res = new ArrayList<>();
if (m == 0 || n == 0) return res;
int cnt = 0;
Arrays.fill(roots, -1);
for (int[] position : positions) {
int pos = position[0] * n + position[1];
roots[pos] = pos;
cnt++;
for (int[] dir : dirs) {
int x = position[0] + dir[0];
int y = position[1] + dir[1];
int next = x * n + y;
if (x < 0 || y < 0 || x >= m || y >= n || roots[next] == -1) continue;
int nextPos = find(roots, next);
if (pos != nextPos) { 如果 四周其中之一 与 当前位置 pos 不一样,union
roots[pos] = nextPos;
pos = nextPos;
cnt--;
}
}
res.add(cnt);
}
return res;
}
public int find(int[] roots, int id) {
while (roots[id] != id) {
id = roots[id];
}
return id;
}