从边界染色,然后在统计内部1的个数。
const int dx[] = {1, 0, 0, -1};
const int dy[] = {0, 1, -1, 0};
class Solution {
public:
int numEnclaves(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
function<void(int,int)> dfs = [&](int x, int y) {
grid[x][y] = 0;
for (int k = 0; k < 4; k++) {
int a = x + dx[k];
int b = y + dy[k];
if (a >= 0 && a < n && b >= 0 && b < m && grid[a][b]) {
dfs(a, b);
}
}
};
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == m - 1) {
if (grid[i][j] == 1) {
dfs(i, j);
}
}
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j]) {
res++;
}
}
}
return res;
}
};