Skip to content

Commit 313a4f6

Browse files
Create 1254_Number of Closed Islands.cpp
1 parent 3d8d6ee commit 313a4f6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
int closedIsland(vector<vector<int>>& grid) {
4+
int m = grid.size();
5+
int n = grid[0].size();
6+
vector<vector<bool>> visit(m, vector<bool>(n));
7+
int count = 0;
8+
for(int i = 0; i < m; i++){
9+
for(int j = 0; j < n; j++){
10+
if(grid[i][j] == 0 && !visit[i][j] && bfs(i, j, m, n, grid, visit)){
11+
count++;
12+
}
13+
}
14+
}
15+
return count;
16+
}
17+
18+
19+
20+
bool bfs(int x, int y, int m, int n, vector<vector<int>>& grid, vector<vector<bool>>& visit){
21+
queue<pair<int,int>> q;
22+
q.push({x, y});
23+
visit[x][y] = 2;
24+
bool isclosed = true;
25+
26+
vector<int> dirx{0, 1, 0, -1};
27+
vector<int> diry{-1, 0, 1, 0};
28+
29+
while(!q.empty()){
30+
x = q.front().first;
31+
y = q.front().second;
32+
q.pop();
33+
34+
for(int i = 0; i < 4; i++){
35+
int r = x + dirx[i];
36+
int c = y + diry[i];
37+
if(r < 0 || r >= m || c < 0 || c >= n){
38+
isclosed = false;
39+
}
40+
else if(grid[r][c] == 0 && !visit[r][c]){
41+
q.push({r, c});
42+
visit[r][c] = true;
43+
}
44+
}
45+
}
46+
47+
return isclosed;
48+
}
49+
50+
};

0 commit comments

Comments
 (0)