-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path305.cpp
More file actions
70 lines (64 loc) · 1.48 KB
/
305.cpp
File metadata and controls
70 lines (64 loc) · 1.48 KB
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
class DSU{
private:
vector<int> parent;
vector<int> rank;
int count;
public:
DSU(int n){
count = 0;
parent.resize(n,-1);
rank.resize(n,0);
}
int Find(int u){
if(parent[u]!=u)
parent[u] = Find(parent[u]);
return parent[u];
}
void Union(int u, int v){
u = Find(u); v = Find(v);
if(u!=v){
if(rank[u]<rank[v])
swap(u,v);
parent[v] = u;
if(rank[u]==rank[v])
rank[u]++;
count--;
}
return;
}
int getCount(){
return count;
}
bool check(int u){
return parent[u]>=0;
}
void init(int u){
if(parent[u] == -1){
parent[u] = u;
count++;
}
}
};
class Solution {
public:
int dirs[5] = {-1,0,1,0,-1};
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
vector<int> res;
DSU ds(n*m);
for(auto& pos: positions){
int r = pos[0];
int c = pos[1];
int u = r*n + c;
ds.init(u);
for(int i=0; i<4; i++){
int nr = r + dirs[i];
int nc = c + dirs[i+1];
int v = nr*n + nc;
if(nr>=0 && nc>=0 && nr<m && nc<n && ds.check(v))
ds.Union(u,v);
}
res.push_back(ds.getCount());
}
return res;
}
};