LeetCode 1020. 飞地的数量

1020. 飞地的数量

 

【BFS】其实这道题就是统计每一个不与边界相连的陆地的个数,可以对每个不在边界上的陆地进行BFS,如果他和边界相连且边界是陆地,那么把本次BFS结束后的所有点设置为海洋,也就是标记这些点为不符合要求;然后再对后面的不在边界上的陆地也进行BFS即可。

class Solution {

    // 12:59 11
    // bfs

    int m, n;
    int[][] grid;
    int[][] d = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    int bfs(int x, int y) {
        int res = 1, flag = 1;
        Queue queue = new LinkedList();
        grid[x][y] = 0;
        queue.offer(new int[] {x, y});
        while (!queue.isEmpty()) {
            int[] top = queue.poll();
            for (var i = 0; i < 4; i++) {
                int nx = top[0] + d[i][0], ny = top[1] + d[i][1];
                if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1) {
                    if (nx == 0 || nx == m - 1 || ny == 0 || ny == n - 1) flag = -1;
                    grid[nx][ny] = 0;
                    res++;
                    queue.offer(new int[] {nx, ny});
                }
            } 
        }
        return flag == -1? -1: res;
    }

    public int numEnclaves(int[][] grid) {
        m = grid.length; n = grid[0].length;
        this.grid = grid;
        int ans = 0;
        for (var i = 1; i < m - 1; i++) {
            for (var j = 1; j < n - 1; j++) {
                if (grid[i][j] == 1) {
                    int ret = bfs(i, j);
                    if (ret != -1) ans += ret;
                }
            }
        }
        return ans;
    }
}

【DFS】

class Solution {

    // DFS
    // 3:15 15

    int m, n;
    int[][] grid;
    int[][] d = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    int dfs(int x, int y) {
        int res = 1, flag = 1;
        for (var i = 0; i < 4; i++) {
            int nx = x + d[i][0];
            int ny = y + d[i][1];
            if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1) {
                if (nx == 0 || nx == m - 1 || ny == 0 || ny == n - 1) flag = -1;
                grid[nx][ny] = 0;
                int ret = dfs(nx, ny);
                if (ret == 0) flag = -1;
                else res += ret;
            }
        }
        return flag == -1 ? 0: res;
    }

    public int numEnclaves(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        this.grid = grid;
        int ans = 0;
        for (var i = 1; i < m - 1; i++) {
            for (var j = 1; j < n - 1; j++) {
                if (grid[i][j] == 1) {
                    grid[i][j] = 0;
                    ans += dfs(i, j);
                }
            }
        }
        return ans;
    }
}

 

 

 

你可能感兴趣的:(LeetCode,leetcode,DFS,BFS)