200、岛屿数量

  1. 200、岛屿数量
    1. 示例 1:
    2. 示例 2:
  2. 题解
    1. 1、深度优先搜索,找到所有的连通域
    2. 2、广度优先搜索
    3. 3、并查集

200、岛屿数量

给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

示例 1:

输入:
11110
11010
11000
00000
输出: 1

示例 2:

输入:
11000
11000
00100
00011
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。

链接:https://leetcode-cn.com/problems/number-of-islands

题解

1、深度优先搜索,找到所有的连通域

// 自己的实现
class Solution {
    int count,m,n;
    int[][] seen; // 访问标记数组
    int[][] dirc = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};
    public int numIslands(char[][] grid) {
        // 获取矩阵参数
        count = 0;
        m = grid.length;
        if (m > 0){
            n = grid[0].length;
        }else{
            return 0;
        }
        // 初始化访问数组
        seen = new int[m][n];
        for (int i = 0;i < m;i++) {
            for (int j = 0;j < n;j++) {
                if(grid[i][j] == '0'){
                    seen[i][j] = 1;
                }
            }
        }
        // 对于每个“陆地”位置进行深度优先搜索
        int res = 0;
        for (int i = 0;i < m;i++) {
            for (int j = 0;j < n;j++) {
                // 对于每个“陆地”位置进行深度优先搜索
                if(grid[i][j] == '1'){
                    dfs(grid,i,j);
                }
                // 陆地面积大于1,岛屿数量+1
                if (count > 0) {
                    res++;
                }
                // 重置陆地面积
                count = 0;
            }
        }
        return res;
    }

    private void dfs(char[][] grid,int i,int j){
        // 非法位置 或者 已经被访问过
        if (i < 0 || i >= m || j < 0 || j >= n || seen[i][j] == 1){
            return;
        }
        // 标记(i,j)处已被访问
        seen[i][j] = 1;
        // 陆地面积+1
        count++;
        // 遍历四联通方向
        for (int k = 0;k < 4;k++) {
            int ni = i + dirc[k][0];
            int nj = j + dirc[k][1];
            if (ni >= 0 && ni < m && nj >= 0 && nj < n && seen[ni][nj] == 0) {
                // 继续深度优先搜索
                dfs(grid,ni,nj);
            }
        }
    }
}

官方题解实现:

  • 利用网格自身数据来标记访问
  • 实现尾递归的深度优先搜索
class Solution {
    int nr;
    int nc;
    void dfs(char[][] grid, int r, int c) {

        if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
            return;
        }

        grid[r][c] = '0';
        // 尾递归
        dfs(grid, r - 1, c);
        dfs(grid, r + 1, c);
        dfs(grid, r, c - 1);
        dfs(grid, r, c + 1);
    }

    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        nr = grid.length;
        nc = grid[0].length;
        int num_islands = 0;
        for (int r = 0; r < nr; ++r) {
            for (int c = 0; c < nc; ++c) {
                if (grid[r][c] == '1') {
                    ++num_islands;
                    // 递归会将所有的连通的陆地都置位0,不必担心重复记录
                    dfs(grid, r, c);
                }
            }
        }

        return num_islands;
    }
}

// 作者:LeetCode
// 链接:https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-shu-liang-by-leetcode/

2、广度优先搜索

class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int nr = grid.length;
        int nc = grid[0].length;
        int num_islands = 0;

        for (int r = 0; r < nr; ++r) {
            for (int c = 0; c < nc; ++c) {
                // 对于每个陆地进行广度优先搜索
                if (grid[r][c] == '1') {
                    ++num_islands;
                    grid[r][c] = '0';
                    // 将二维存储成一维
                    Queue<Integer> neighbors = new LinkedList<>();
                    neighbors.add(r * nc + c);
                    while (!neighbors.isEmpty()) {
                        int id = neighbors.remove();
                        int row = id / nc;
                        int col = id % nc;
                        if (row - 1 >= 0 && grid[row-1][col] == '1') {
                            neighbors.add((row-1) * nc + col);
                            grid[row-1][col] = '0';
                        }
                        if (row + 1 < nr && grid[row+1][col] == '1') {
                            neighbors.add((row+1) * nc + col);
                            grid[row+1][col] = '0';
                        }
                        if (col - 1 >= 0 && grid[row][col-1] == '1') {
                            neighbors.add(row * nc + col-1);
                            grid[row][col-1] = '0';
                        }
                        if (col + 1 < nc && grid[row][col+1] == '1') {
                            neighbors.add(row * nc + col+1);
                            grid[row][col+1] = '0';
                        }
                    }
                }
            }
        }

        return num_islands;
    }
}

// 作者:LeetCode
// 链接:https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-shu-liang-by-leetcode/

3、并查集

class Solution {
    // 并查集类
    class UnionFind {
        int count;
        int[] parent;
        // rank分类之后为find方法优化了,使得find的时候能够达到O(h)级别(就是parent树的高度)吧。
        // 并查集的优化有按秩合并和路径压缩两种,这里的rank数组就是秩,其实就是树的高度,也就是说每次合并的时候要把高度小的树插入到高度大的树上,这样除非两个树高度相等,否则插入后树的高度也不会变的。
        int[] rank;

        public UnionFind(char[][] grid) {
            // 统计连通域
            count = 0;
            int m = grid.length;
            int n = grid[0].length;
            parent = new int[m * n];
            rank = new int[m * n];
            // 初始化parent数组和rank数组
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (grid[i][j] == '1') {
                        parent[i * n + j] = i * n + j;
                        ++count;
                    }
                    rank[i * n + j] = 0;
                }
            }
        }

        public int find(int i) {
            // 递归找到祖先
            if (parent[i] != i) parent[i] = find(parent[i]);
            return parent[i];
        }

        public void union(int x, int y) {
            // 找x的祖先
            int rootx = find(x);
            // 找y的祖先
            int rooty = find(y);
            // 不是同一个祖先,进行合并
            if (rootx != rooty) {
                // 深的节点要以浅的节点为祖先
                if (rank[rootx] > rank[rooty]) {
                    parent[rooty] = rootx;
                } else if (rank[rootx] < rank[rooty]) {
                    parent[rootx] = rooty;
                } else {
                    parent[rooty] = rootx;
                    rank[rootx] += 1;
                }
                --count;
            }
        }
        // 获取连通域的个数
        public int getCount() {
            return count;
        }
    }

    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int nr = grid.length;
        int nc = grid[0].length;
        int num_islands = 0;
        UnionFind uf = new UnionFind(grid);
        for (int r = 0; r < nr; ++r) {
            for (int c = 0; c < nc; ++c) {
                // 对于每个陆地,按照上下左右进行合并
                if (grid[r][c] == '1') {
                    grid[r][c] = '0';
                    if (r - 1 >= 0 && grid[r-1][c] == '1') {
                        uf.union(r * nc + c, (r-1) * nc + c);
                    }
                    if (r + 1 < nr && grid[r+1][c] == '1') {
                        uf.union(r * nc + c, (r+1) * nc + c);
                    }
                    if (c - 1 >= 0 && grid[r][c-1] == '1') {
                        uf.union(r * nc + c, r * nc + c - 1);
                    }
                    if (c + 1 < nc && grid[r][c+1] == '1') {
                        uf.union(r * nc + c, r * nc + c + 1);
                    }
                }
            }
        }

        return uf.getCount();
    }
}

// 作者:LeetCode
// 链接:https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-shu-liang-by-leetcode/

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:200、岛屿数量

Count:1.6k

Author:攀登

Created At:2020-07-26, 00:19:44

Updated At:2024-06-15, 15:52:32

Url:http://jiafeimao-gjf.github.io/2020/07/26/200%E3%80%81%E5%B2%9B%E5%B1%BF%E6%95%B0%E9%87%8F/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation