讨论/《深度优先搜索》 - 练习:飞地的数量/
《深度优先搜索》 - 练习:飞地的数量
共 2 个回复
class Solution {
     int[][] direction = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
    public int numEnclaves(int[][] grid) {
        if (grid.length == 0) return 0;
        int m = grid.length;
        int n = grid[0].length;
        int count = 0;
        boolean[][] visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            if (grid[i][0] == 1) dfs(grid, i, 0, visited);
             if (grid[i][n-1] == 1) dfs(grid, i, n-1, visited);
        }

        for (int i = 0; i < n; i++) {
            if (grid[0][i] == 1) dfs(grid, 0, i, visited);
            if (grid[m-1][i] == 1) dfs(grid,m-1, i, visited);
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) count++;
            }
        }
        return count;
    }

    private void dfs(int[][] grid, int i, int j, boolean[][] visited) {

        visited[i][j] = true;
        grid[i][j] = 0;
        for (int k = 0; k < 4; k++) {
            int x = i+direction[k][0];
            int y = j+direction[k][1];
            if (isArea(grid,x,y)&&grid[x][y]==1)
                dfs(grid, x, y, visited);
        }

    }

    public boolean isArea(int[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;
        return true;
    }
}
class Solution {
public:
    void dfs(vector<vector<int>>& grid , int i, int j){
        int m=grid.size();
        int n=grid[0].size();
        if(i<0 || i>=m || j<0 || j>=n || grid[i][j]==0)
            return;

        grid[i][j]=0;
        dfs(grid, i-1, j);
        dfs(grid, i+1, j);
        dfs(grid, i, j-1);
        dfs(grid, i, j+1);
    }

    int numEnclaves(vector<vector<int>>& grid) {
        //dfs from border
        int m=grid.size();
        int n=grid[0].size();
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if((i==0||i==m-1||j==0||j==n-1) && grid[i][j]==1){
                    dfs(grid, i, j);
                }   
            }
        }
        int count=0;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j]==1)
                    count++;
            }
        }
        return count;
    }
};