前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >​LeetCode刷题实战200:岛屿数量

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

作者头像
程序员小猿
发布2021-03-06 22:35:10
3420
发布2021-03-06 22:35:10
举报
文章被收录于专栏:程序IT圈

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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'(水)组成的的二维网格,请你计算网格中岛屿的数量。

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

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

示例

代码语言:javascript
复制
示例 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。

代码语言:javascript
复制
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);
    }
}

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-03-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 示例
  • 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档