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.

Example 1:

Input:
11110
11010
11000
00000 Output: 1

Example 2:

Input:
11000
11000
00100
00011 Output: 3

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

这道求岛屿数量的题的本质是求矩阵中连续区域的个数,很容易想到需要用深度优先搜索 DFS 来解,我们需要建立一个 visited 数组用来记录某个位置是否被访问过,对于一个为 ‘1’ 且未被访问过的位置,递归进入其上下左右位置上为 ‘1’ 的数,将其 visited 对应值赋为 true,继续进入其所有相连的邻位置,这样可以将这个连通区域所有的数找出来,并将其对应的 visited 中的值赋 true,找完相邻区域后,将结果 res 自增1,然后再继续找下一个为 ‘1’ 且未被访问过的位置,以此类推直至遍历完整个原数组即可得到最终结果,代码如下:

解法一:

class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[].empty()) return ;
int m = grid.size(), n = grid[].size(), res = ;
vector<vector<bool>> visited(m, vector<bool>(n));
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (grid[i][j] == '' || visited[i][j]) continue;
helper(grid, visited, i, j);
++res;
}
}
return res;
}
void helper(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) {
if (x < || x >= grid.size() || y < || y >= grid[].size() || grid[x][y] == '' || visited[x][y]) return;
visited[x][y] = true;
helper(grid, visited, x - , y);
helper(grid, visited, x + , y);
helper(grid, visited, x, y - );
helper(grid, visited, x, y + );
}
};

当然,这种类似迷宫遍历的题目 DFS 和 BFS 两对好基友肯定是形影不离的,那么 BFS 搞起。其实也很简单,就是在遍历到 ‘1’ 的时候,且该位置没有被访问过,那么就调用一个 BFS 即可,借助队列 queue 来实现,现将当前位置加入队列,然后进行 while 循环,将队首元素提取出来,并遍历其周围四个位置,若没有越界的话,就将 visited 中该邻居位置标记为 true,并将其加入队列中等待下次遍历即可,参见代码如下:

解法二:

class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[].empty()) return ;
int m = grid.size(), n = grid[].size(), res = ;
vector<vector<bool>> visited(m, vector<bool>(n));
vector<int> dirX{-, , , }, dirY{, , , -};
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (grid[i][j] == '' || visited[i][j]) continue;
++res;
queue<int> q{{i * n + j}};
while (!q.empty()) {
int t = q.front(); q.pop();
for (int k = ; k < ; ++k) {
int x = t / n + dirX[k], y = t % n + dirY[k];
if (x < || x >= m || y < || y >= n || grid[x][y] == '' || visited[x][y]) continue;
visited[x][y] = true;
q.push(x * n + y);
}
}
}
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/200

类似题目:

Number of Islands II

Surrounded Regions

Walls and Gates

Number of Connected Components in an Undirected Graph

Number of Distinct Islands

Max Area of Island

参考资料:

https://leetcode.com/problems/number-of-islands/

https://leetcode.com/problems/number-of-islands/discuss/56589/C%2B%2B-BFSDFS

https://leetcode.com/problems/number-of-islands/discuss/56359/Very-concise-Java-AC-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Number of Islands 岛屿的数量的更多相关文章

  1. [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 surro ...

  2. [LintCode] Number of Islands 岛屿的数量

    Given a boolean 2D matrix, find the number of islands. Notice 0 is represented as the sea, 1 is repr ...

  3. LeetCode Number of Islands 岛的数量(DFS,BFS)

    题意:0代表水,1代表陆地,那么被水围起来的就是岛了,给一个01矩阵,问有多少个岛? 思路:DFS还是比较短,实现了一下.如果一个点已经被遍历过了,那就将其置为0就行了,不要去搜0的. class S ...

  4. [LeetCode] Number of Islands II 岛屿的数量之二

    A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...

  5. LeetCode 200. Number of Islands 岛屿数量(C++/Java)

    题目: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is s ...

  6. 【LeetCode】200. Number of Islands 岛屿数量

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  7. [LeetCode] 0200. Number of Islands 岛屿的个数

    题目 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is su ...

  8. [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 surro ...

  9. Leetcode: Number of Islands II && Summary of Union Find

    A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...

随机推荐

  1. 深入浅出JavaScript之this

    JavaScript中的this比较灵活,根据在不同环境下,或者同一个函数在不同方式调用下,this都有可能是不同的.但是有一个总的原则,那就是this指的是,调用函数的那个对象. 下面是我的学习笔记 ...

  2. 微信小程序定时器组件(输入时间字符串即可倒计时)

    昨天写了代码,今天发现要重用,干脆就抽出来做个组件得了,顺便还改善了一下代码通用性. 昨天的代码在这里 github下载地址 用法: 引入: var timer = require('../../pl ...

  3. c#编程基础之函数可变参数

    可变参数:int sum (params int[] values)int sum (string name,params int[] values) 注意:params参数必须是形参表中的最后一个参 ...

  4. code

    using System;using System.Threading; namespace ThreadLocalTest{    public class MyObject    {       ...

  5. C++ map的基本操作和使用

    原文地址:http://blog.sina.com.cn/s/blog_61533c9b0100fa7w.html Map是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可 ...

  6. 【python常用函数1】

    ## 1 ##获取输入值 a = raw_input("请输入:") if a == str(1): print "success" else: print & ...

  7. Java内部类学习笔记

    20160923 定义:将一个类的定义放在另一个类的内部: 从外部类的非静态方法之外,创建某个内部类的对象:OutClassName.InnerClassName: 内部类拥有所有其外部类的成员的访问 ...

  8. windows7 x64下maven安装和配置

    http://maven.apache.org/download.cgi下载maven 环境配置 验证配置是否成功 本地仓库配置 这是原来的配置文件: 更改为: link 离线安装 eclipse m ...

  9. Java面试题整理二(侧重SSH框架)

    1.持久化对象的状态都有哪些? 答:瞬时对象(Transient Objects):使用new 操作符初始化的对象不是立刻就持久的.它们的状态是瞬时的,也就是说它们没有任何跟数据库表相关联的行为,只要 ...

  10. yii2的权限管理系统RBAC简单介绍

    这里有几个概念 权限: 指用户是否可以执行哪些操作,如:编辑.发布.查看回帖 角色 比如:VIP用户组, 高级会员组,中级会员组,初级会员组 VIP用户组:发帖.回帖.删帖.浏览权限 高级会员组:发帖 ...