Breadth-first search.
First mark all location access as false if the location is 1 ans++ (count the number of all 1 locations)
then mark the cell that can leave the grid boundary as true and then set the access to the grid connected to it by breadth first search to 1 then ans-- subtract it
class Solution {
public:
bool vis[510][510];
int xx[4]={
1,-1,0,0};
int yy[4]={
0,0,1,-1};
int numEnclaves(vector<vector<int>>& grid) {
int ans=0;
int m=grid.size(),n=grid[0].size();
queue<pair<int,int>> q;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==1)ans++;
vis[i][j]=false;
if(i==0||j==0||i==m-1||j==n-1){
if(grid[i][j]==1){
q.push({
i,j});
vis[i][j]=true;
}
}
}
}
while(!q.empty()){
auto t=q.front();
q.pop();
int x=t.first,y=t.second;
ans--;
for(int k=0;k<4;k++){
int dx=x+xx[k];
int dy=y+yy[k];
if(dx<0||dx>=m||dy<0||dy>=n)continue;
if(!vis[dx][dy]&&(grid[dx][dy]==1)){
vis[dx][dy]=true;
q.push({
dx,dy});
}
}
}
return ans;
}
};