【宽度优先搜索 BFS】LeetCode-200. 岛屿数量

2023-12-21 11:21:39
200. 岛屿数量。

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

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

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

示例 1:

输入:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出:1

示例 2:

输入:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出:3

提示:

m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
算法分析

解题思路

思路(flood fill算法 dfs实现):
用dfs枚举整个地图,若当前位置是 1,则把这个位置赋值为 0,然后遍历上下左右四个方向,将所有为1的地方赋值为 0,当这块岛屿已经遍历完,则 答案加1 。

class Solution {
    int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1}; 
    public int numIslands(char[][] g) {
        int n = g.length;
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < g[i].length; j++) {
                if (g[i][j] == '1') {
                    dfs(g, i, j);
                    cnt++;
                }
            }
        }
        return cnt;
    }

    private void dfs(char[][] g, int i, int j) {
        g[i][j] = '0';
        for (int m = 0; m < 4; m++) {
            int x = i + dx[m], y = j + dy[m];
            if (x >= 0 && x < g.length && y >= 0 && y < g[x].length && g[x][y] == '1') {
                dfs(g, x, y);
            }
        }
    }

}

复杂性分析

时间复杂度:O(nm)
空间复杂度:O(nm)

文章来源:https://blog.csdn.net/xiaoxiawancsdn/article/details/135122908
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。