[LintCode] Problem 434 - Number of Islands II

Given a n,m which means the row and column of the 2D matrix and an array of pair A(size k). Originally, the 2D matrix is all 0 which means there is only sea in the matrix. The list pair has k operator and each operator has two integer A[i].x, A[i].y means that you can change the grid matrix[A[i].x][A[i].y] from sea to island. Return how many island are there in the matrix after each operator.

Note

0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Example

No.1

Input: n = 4, m = 5, A = [[1,1],[0,1],[3,3],[3,4]]

Output: [1,1,2,2]

Explanation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0.  00000
00000
00000
00000
1. 00000
01000
00000
00000
2. 01000
01000
00000
00000
3. 01000
01000
00000
00010
4. 01000
01000
00000
00011

No.2

Input: n = 3, m = 3, A = [[0,0],[0,1],[2,2],[2,1]]

Output: [1,1,2,2]

Code

1
2
3
4
5
6
public class Point {
int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class UnionFind{
private int[] id;
private int[] size;
private int count;

public UnionFind(int n) {
this.id = new int[n+1];
this.size = new int[n+1];
this.count = n;

for (int i = 1; i <= n; i++) {
id[i] = i;
size[i] = 1;
}
}

public int count() {
return count;
}

public boolean union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);

if (pRoot == qRoot)
return false;

if (size[pRoot] < size[qRoot]) {
id[pRoot] = qRoot;
size[qRoot] += size[pRoot];
}
else {
id[qRoot] = pRoot;
size[pRoot] += size[qRoot];
}

count--;
return true;
}

public int find(int p) {
while (p != id[p])
p = id[p];

return p;
}
}

public List<Integer> numIslands2(int n, int m, Point[] operators) {
List<Integer> result = new ArrayList<>();

if (operators == null || operators.length == 0)
return result;

int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Set<Integer> island = new HashSet<>();
UnionFind uf = new UnionFind(n * m);

for (Point operator : operators) {
int idx = operator.x * m + operator.y;
island.add(idx);

for (int[] dir : dirs) {
int x = operator.x + dir[0];
int y = operator.y + dir[1];
int newIdx = x * m + y;

if (x < 0 || y < 0 || x >= n || y >= m || !island.contains(newIdx))
continue;

uf.union(idx, newIdx);
}

result.add(uf.count() - n * m + island.size());
}

return result;
}