-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Number Of Islands
60 lines (56 loc) · 1.62 KB
/
GFG Number Of Islands
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
// Back-end complete function Template for C++
class Solution {
public:
int p[100000];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int index(int x, int y, int m)
{
return x * m + y;
}
vector<int> numOfIslands(int n, int m, vector<vector<int>> &operators) {
if (operators.empty())
return {};
vector<int> res;
unordered_set<int> nodes;
int s = operators.size();
unordered_set<int> current;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int total = 0;
for(auto op : operators){
int pos = index(op[0], op[1], m);
nodes.insert(pos);
if (current.count(pos))
{
res.push_back(total);
continue;
}
total++;
p[pos] = pos;
for (int j = 0; j < 4; j++)
{
int nx = op[0] + dx[j];
int ny = op[1] + dy[j];
if (!(nx >= 0 && nx < n && ny >= 0 && ny < m))
continue;
if (current.count(index(nx, ny, m)))
{
int apos = index(op[0], op[1], m);
int bpos = index(nx, ny, m);
if (find(apos) != find(bpos))
{
p[find(apos)] = find(bpos);
total--;
}
}
}
current.insert(index(op[0], op[1], m));
res.push_back(total);
}
return res;
}
};