1020. 飞地的数量

题目:

思路:

【1】常规的遍历题

代码展示:

//时间6 ms 击败 97.46%
//内存53.1 MB 击败 74.43%
class Solution {
    public int numEnclaves(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        // 先将能抵达边界的陆地都变为海域
        for (int i = 0; i < m; i++) {
            dfs(grid, i, 0);
            dfs(grid, i, n - 1);
        }
        for (int i = 0; i < n; i++) {
            dfs(grid, 0, i);
            dfs(grid, m - 1, i);
        }
        // 检索剩下的不能达到边界的陆地
        int num = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    num++;
                }
            }
        }
        return num;
    }
    
    private void dfs(int[][] grid, int row, int col) {
        if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1) {
            grid[row][col] = 0;
            dfs(grid, row + 1, col);
            dfs(grid, row - 1, col);
            dfs(grid, row, col + 1);
            dfs(grid, row, col - 1);
        }
    }
}

 

posted @ 2023-08-21 12:23  忧愁的chafry  阅读(6)  评论(0编辑  收藏  举报