- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution_dfs.cpp
30 lines (29 loc) · 833 Bytes
/
solution_dfs.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
// DFS
classSolution {
public:
intnumEnclaves(vector<vector<int>>& g) {
int n = g.size(), m = g[0].size();
int ans = 0;
vector<int> d{0, 1, 0, -1, 0};
function<bool(int, int, int &)> dfs = [&](int i, int j, int &cnt) {
if(i < 0 || j < 0 || i >= n || j >= m)
returntrue;
if(g[i][j] == 0)
returnfalse;
g[i][j] = 0;
cnt++;
bool flag = false;
for(int k = 0; k < 4; k++)
flag |= dfs(i + d[k], j + d[k + 1], cnt);
return flag;
};
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int cnt = 0;
if(!dfs(i, j, cnt))
ans += cnt;
}
}
return ans;
}
};