[LeetCode] Number of Islands II

305. Number of Islands II

You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0’s represent water and 1’s represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0’s).

We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.

Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.

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.

  • Time : O(p * lognm)
  • Space : O(nm)
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
class Solution {
int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0};
unordered_map<int, int> group;
unordered_map<int, int> grid[10000];

int find(int n) {
return group[n] == n ? n : group[n] = find(group[n]);
}

unordered_set<int> near(int y, int x, int n, int m) {
unordered_set<int> res;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and grid[ny].count(nx)) {
res.insert( find(grid[ny][nx]));
}
}
return res;
}

void uni(unordered_set<int> islands) {
int mi = *min_element(islands.begin(),islands.end());
for(auto island : islands) {
group[island] = mi;
}
}
public:
vector<int> numIslands2(int n, int m, vector<vector<int>>& positions) {
vector<int> res;
int island = 0;
int cnt = 0;
for(auto po : positions) {
int y = po[0], x = po[1];
if(grid[y].count(x)) {
res.push_back(cnt);
continue;
}
auto neighbor = near(y,x,n,m);
if(neighbor.empty()) {
grid[y][x] = ++island;
group[island] = island;
cnt++;
} else if(neighbor.size() == 1) {
grid[y][x] = *neighbor.begin();
} else {
grid[y][x] = *min_element(neighbor.begin(), neighbor.end());
cnt -= (neighbor.size() - 1);
uni(neighbor);
}
res.push_back(cnt);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/number-of-islands-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.