Skip to content

Latest commit

 

History

History
58 lines (47 loc) · 1.51 KB

9.md

File metadata and controls

58 lines (47 loc) · 1.51 KB
 void dfs(vector<vector<int>>& grid,int i,int j,vector<vector<int>>&visited,int n,int  m)
    {
        visited[i][j]=1;
        int drow[]={-1,0,1,0};
        int dcol[]={0,1,0,-1};

        for(int it=0;it<4;it++)
        {
            int ro=drow[it]+i;
            int co=dcol[it]+j;

            if(ro>=0 && ro<n && co>=0 && co<m && grid[ro][co]==1 && visited[ro] [co]!=1)
                    dfs(grid,ro,co,visited,n,m);
        } 
    }
    int numEnclaves(vector<vector<int>>& grid) {
        
        int n=grid.size();
        int m=grid[0].size();

        vector<vector<int>>visited(n,vector<int>(m,0));

        //first row
        for(int c=0;c<m;c++)
        {
            if(grid[0][c]==1 && visited[0][c]!=1)
                dfs(grid,0,c,visited,n,m);
        }

        //last row
        for(int c=0;c<m;c++)
        {
            if(grid[n-1][c]==1 && visited[n-1][c]!=1)
               dfs(grid,n-1,c,visited,n,m);
        }

        //first col
        for(int i=0;i<n;i++)
            if(grid[i][0]==1 && visited[i][0]!=1)
                dfs(grid,i,0,visited,n,m);

        //last col
        for(int i=0;i<n;i++)
            if(grid[i][m-1]==1 && visited[i][m-1]!=1)
                dfs(grid,i,m-1,visited,n,m);

        int ans=0;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                if(grid[i][j]==1 && visited[i][j]!=1)
                    ans++;

        return ans;
    }