File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int closedIsland(vector<vector<int>>& g) {
4+ queue<pair<int,int>>q;
5+ int n=g.size(),m=g[0].size();
6+ for(int i=0;i<n;i++){
7+ for(int j=0;j<m;j++){
8+ if(i==0 || i==n-1 || j==0 || j==m-1){
9+ if(g[i][j]==0){
10+ g[i][j]=1;
11+ q.push({i,j});}
12+ }
13+ }
14+ }
15+ while(q.size()){
16+ auto l=q.front();
17+ q.pop();
18+ int x=l.first;
19+ int y=l.second;
20+ int dx[4]={1,-1,0,0};
21+ int dy[4]={0,0,1,-1};
22+ for(int i=0;i<4;i++){
23+ int nx=dx[i]+x;
24+ int ny=dy[i]+y;
25+ if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==0){
26+ g[nx][ny]=1;
27+ q.push({nx,ny});
28+ }
29+ }
30+ }
31+ int ct=0;
32+ for(int i=0;i<n;i++){
33+ for(int j=0;j<m;j++){
34+ if(!g[i][j]){
35+ ct++;
36+ q.push({i,j});
37+ while(q.size()){
38+ auto l=q.front();
39+ q.pop();
40+ int x=l.first;
41+ int y=l.second;
42+ int dx[4]={1,-1,0,0};
43+ int dy[4]={0,0,1,-1};
44+ for(int i=0;i<4;i++){
45+ int nx=dx[i]+x;
46+ int ny=dy[i]+y;
47+ if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==0){
48+ g[nx][ny]=1;
49+ q.push({nx,ny});
50+ }
51+ }
52+ }
53+ }
54+ }
55+ }
56+ return ct;
57+ }
58+ };
You can’t perform that action at this time.
0 commit comments