Leetcode 200. Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

思路:碰见是1的点就进行宽度搜索,并把它的所有邻岛标记为0,总岛数+1.

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

    int res = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == '1') {
                bfs(grid, i, j);
                res++;
            }
        }
    }

    return res;
}

private void bfs(char[][] grid, int i, int j) {
    int[] dx = {0, 1, 0, -1};
    int[] dy = {1, 0, -1, 0};
    Queue<int[]> q = new LinkedList<>();
    int[] coor = {i, j};
    q.offer(coor);
    while (!q.isEmpty()) {
        int[] cur = q.poll();
        grid[cur[0]][cur[1]] = '0';
        for (int k = 0; k < 4; k++) {
            int tx = cur[0] + dx[k];
            int ty = cur[1] + dy[k];
            if (tx < 0 || tx >= grid.length || ty < 0 || ty >= grid[0].length || grid[tx][ty] == '0') {
                continue;
            }
            int[] neighbor = {tx, ty};
            q.offer(neighbor);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Number of Islands Given a 2d grid map of '1's (land) and ...
    gammaliu阅读 2,981评论 0 0
  • Problem Given a 2d grid map of '1's (land) and '0's (wate...
    Branch阅读 4,099评论 0 1
  • 分析 只需要对每一个陆地区域做一次dfs,每次dfs中将已经遍历的陆地网格“1”变为水域网格“0”(防止再次遍历导...
    胡哈哈哈阅读 2,910评论 0 0
  • 原题 给一个01矩阵,求不同的岛屿的个数。0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑...
    Jason_Yuan阅读 3,978评论 0 0
  • 今天看了凤红邪的文章,觉得太对了。 让我想起来,从小大家就是总是说我这里好那里好,或者说别人家的孩子怎么好。结果我...
    Yoscool阅读 3,996评论 6 4

友情链接更多精彩内容