Skip to content

Commit 990cf24

Browse files
authored
1254. Number of Closed Islands
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands.
1 parent cfcf829 commit 990cf24

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

closed.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
int closedIsland(vector<vector<int>>& grid) {
4+
if(grid.empty() || grid[0].empty()) return 0;
5+
int h = grid.size();
6+
int w = grid[0].size();
7+
int count = 0;
8+
int i,j;
9+
for(i=0; i < h; ++i) {
10+
for (j=0; j < w; ++j){
11+
if(grid[i][j]==0) {
12+
count+=dfs(grid, i , j)?1:0;
13+
}
14+
}
15+
}
16+
return count;
17+
}
18+
19+
private:
20+
bool dfs(vector<vector<int>>&grid, int i, int j) {
21+
if (i < 0 || j < 0|| i >= grid.size() || j >= grid[0].size()) {
22+
return false;
23+
}
24+
if (grid[i][j]==1) return true;
25+
grid[i][j] = 1;
26+
bool d1 = dfs(grid, i+1, j);
27+
bool d2 = dfs(grid, i-1, j);
28+
bool d3 = dfs(grid, i, j+1);
29+
bool d4 = dfs(grid, i, j-1);
30+
return d1 && d2 && d3 && d4;
31+
32+
}
33+
};

0 commit comments

Comments
 (0)