​LeetCode刷题实战200:岛屿数量

共 3658字,需浏览 8分钟

 ·

2021-03-04 10:16

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 岛屿数量,我们先来看题面:
https://leetcode-cn.com/problems/number-of-islands/

Given an m x n 2d grid map of '1's (land) and '0's (water), return 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

输入: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


解题


我们遍历整个二维数组,当我们遇到为'1'的,我们将其相邻的所有‘1’重置为‘0’,即将这一块岛全部都变为海水然后再去遍历数组剩下的部分。遇到一个岛屿的第一标‘1’的cnt加1。


class Solution {
    public int numIslands(char[][] grid) {
      int cnt = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    depthSearch(grid,i,j);
                    cnt++;
                }
            }
        }
        return cnt;
    }
    public void depthSearch(char[][] grid, int i, int j) {
        if (grid == null ||(i<0 || i >= grid.length) ||( j<0 || j >= grid[i].length)) {
            return;
        }
        if (grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '0';
        depthSearch(grid, i + 1, j) ;
        depthSearch(grid, i - 1, j) ;
        depthSearch(grid, i, j + 1) ;
        depthSearch(grid, i, j - 1);
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-180题汇总,希望对你有点帮助!
LeetCode刷题实战181:超过经理收入的员工
LeetCode刷题实战182:查找重复的电子邮箱
LeetCode刷题实战183:从不订购的客户
LeetCode刷题实战184:部门工资最高的员工
LeetCode刷题实战185:部门工资前三高的所有员工
LeetCode刷题实战186:翻转字符串里的单词 II
LeetCode刷题实战187:重复的DNA序列
LeetCode刷题实战188:买卖股票的最佳时机 IV
LeetCode刷题实战189:旋转数组
LeetCode刷题实战190:颠倒二进制位
LeetCode刷题实战191:位1的个数
LeetCode刷题实战192:统计词频
LeetCode刷题实战193:有效电话号码
LeetCode刷题实战194:转置文件
LeetCode刷题实战195:第十行
LeetCode刷题实战196:删除重复的电子邮箱
LeetCode刷题实战197:上升的温度
LeetCode刷题实战198:打家劫舍
LeetCode刷题实战199:二叉树的右视图

浏览 38
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报