-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1254_Number of Closed Islands.cpp
50 lines (42 loc) · 1.29 KB
/
1254_Number of Closed Islands.cpp
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
class Solution {
public:
int closedIsland(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> visit(m, vector<bool>(n));
int count = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 0 && !visit[i][j] && bfs(i, j, m, n, grid, visit)){
count++;
}
}
}
return count;
}
bool bfs(int x, int y, int m, int n, vector<vector<int>>& grid, vector<vector<bool>>& visit){
queue<pair<int,int>> q;
q.push({x, y});
visit[x][y] = 2;
bool isclosed = true;
vector<int> dirx{0, 1, 0, -1};
vector<int> diry{-1, 0, 1, 0};
while(!q.empty()){
x = q.front().first;
y = q.front().second;
q.pop();
for(int i = 0; i < 4; i++){
int r = x + dirx[i];
int c = y + diry[i];
if(r < 0 || r >= m || c < 0 || c >= n){
isclosed = false;
}
else if(grid[r][c] == 0 && !visit[r][c]){
q.push({r, c});
visit[r][c] = true;
}
}
}
return isclosed;
}
};