forked from Chayandas07/LeetCode-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1254. Number of Closed Islands 6 apr
58 lines (58 loc) · 1.58 KB
/
1254. Number of Closed Islands 6 apr
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
class Solution {
public:
int closedIsland(vector<vector<int>>& g) {
queue<pair<int,int>>q;
int n=g.size(),m=g[0].size();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(i==0 || i==n-1 || j==0 || j==m-1){
if(g[i][j]==0){
g[i][j]=1;
q.push({i,j});}
}
}
}
while(q.size()){
auto l=q.front();
q.pop();
int x=l.first;
int y=l.second;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
for(int i=0;i<4;i++){
int nx=dx[i]+x;
int ny=dy[i]+y;
if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==0){
g[nx][ny]=1;
q.push({nx,ny});
}
}
}
int ct=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!g[i][j]){
ct++;
q.push({i,j});
while(q.size()){
auto l=q.front();
q.pop();
int x=l.first;
int y=l.second;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
for(int i=0;i<4;i++){
int nx=dx[i]+x;
int ny=dy[i]+y;
if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==0){
g[nx][ny]=1;
q.push({nx,ny});
}
}
}
}
}
}
return ct;
}
};