/** * @param {number[][]}grid * @return {number} */ var numEnclaves = function (grid) { let res = 0, flag = true;
const dfs = (i, j) => { if (!grid[i][j]) return0; grid[i][j] = 0; if ( i === 0 || i === grid.length - 1 || j === 0 || j === grid[i].length - 1 ) { flag = false; }
const top = grid[i - 1] && grid[i - 1][j], bottom = grid[i + 1] && grid[i + 1][j], left = grid[i][j - 1], right = grid[i][j + 1];
let res = 0;
if (top) res += dfs(i - 1, j); if (bottom) res += dfs(i + 1, j); if (left) res += dfs(i, j - 1); if (right) res += dfs(i, j + 1);
return res + 1; };
for (let i = 1; i < grid.length; i++) { for (let j = 1; j < grid[i].length; j++) { if (!grid[i][j]) continue; flag = true; count = dfs(i, j); if (flag) res += count; } }