Fork me on GitHub

Number of Islands II

Description

https://leetcode.com/problems/number-of-islands-ii/description/

Solution

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
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> ret;
vector<int> roots(m * n, -1);
vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int count = 0;
for (auto& position : positions) {
int x = position.first;
int y = position.second;
int pos = x * n + y;
if (roots[pos] == -1) {
roots[pos] = pos;
count += 1;
}
for (auto& dir : dirs) {
int newX = x + dir[0];
int newY = y + dir[1];
int newPos = newX * n + newY;
if (newX < 0 || newX >= m || newY < 0 || newY >= n || roots[newPos] == -1) continue;
int rootCur = findRoot(roots, pos);
int rootNew = findRoot(roots, newPos);

if (rootCur != rootNew) {
roots[rootCur] = rootNew;
--count;
}
}
ret.push_back(count);
}

return ret;
}

int findRoot(vector<int>& roots, int pos) {
stack<int> st;
while (roots[pos] != pos) {
pos = roots[pos];
st.push(pos);
}
while(!st.empty()) {
roots[st.top()] = pos;
st.pop();
}
return pos;
}
};