-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumberofClosedIslands.cpp
More file actions
35 lines (34 loc) · 933 Bytes
/
numberofClosedIslands.cpp
File metadata and controls
35 lines (34 loc) · 933 Bytes
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
// Source: https://leetcode.com/problems/number-of-closed-islands/
// Author: Miao Zhang
// Date: 2021-04-20
class Solution {
public:
int closedIsland(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
bool val = 1;
function<void(int, int)> dfs = [&] (int x, int y) {
if (x < 0 || x >= m || y < 0 || y >= n) {
val = 0;
return;
}
if (grid[x][y]) return;
grid[x][y] = 1;
dfs(x + 1, y);
dfs(x - 1, y);
dfs(x, y + 1);
dfs(x, y - 1);
};
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
val = 1;
dfs(i, j);
res += val;
}
}
}
return res;
}
};