您的位置:首页 > 其它

305. Number of Islands II

2016-03-25 12:08 288 查看
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]


Challenge:

Can you do it in time complexity O(k log mn), where k is the length of the
positions
?

Similar:

300. Number of Islands

public class Solution {
public List<Integer> numIslands2(int m, int n, int[][] positions) {
List<Integer> cnt = new ArrayList<Integer>();
int[][] root = new int[m]
;
for (int i=0; i<m; i++)
for (int j=0; j<n; j++) {
root[i][j] = -1;
}
int lastNumber = 0;

for (int[] pt : positions) {
lastNumber = addLand(root, pt[0], pt[1], lastNumber);
cnt.add(lastNumber);
}

return cnt;
}

private int addLand(int[][] root, int r, int c, int num) {
if (root[r][c] != -1) return -1; // used to land this part
int m = root.length;
int n = root[0].length;

root[r][c] = r * n + c; // root is itself
num += 1;

if (r-1>=0 && root[r-1][c]!=-1) { // up
if (union(root, r-1, c, r, c))
num--;
}
if (r+1<m && root[r+1][c]!=-1) { // down
if (union(root, r+1, c, r, c))
num--;
}
if (c-1>=0 && root[r][c-1]!=-1) { // left
if (union(root, r, c-1, r, c))
num--;
}
if (c+1<n && root[r][c+1]!=-1) { // right
if (union(root, r, c+1, r, c))
num--;
}
return num;
}

private boolean union(int[][] grid, int r1, int c1, int r2, int c2) {
int root1 = find(grid, r1, c1);
int root2 = find(grid, r2, c2);

if (root1 == root2) return false; // already in one set

int n = grid[0].length;
int x = root2 / n;
int y = root2 % n;

grid[x][y] = root1;
return true;
}

private int find(int[][] grid, int r, int c) {
int n = grid[0].length;
int id = r * n + c;
int rr, cc;
while (id != grid[r][c]) {
rr = grid[r][c] / n;
cc = grid[r][c] % n;
grid[r][c] = grid[rr][cc];
r = rr;
c = cc;
id = rr * n +cc;
}
return id;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: