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. 读书笔记--SQL必知必会13--创建高级联结

    13.1 使用表别名 SQL可以对列名.计算字段和表名起别名. 缩短SQL语句 允许在一条SELECT语句中多次使用相同的表. 注意:表别名只在查询执行中使用,不返回到客户端. MariaDB [sq ...

  2. 利用Python进行数据分析(2) 尝试处理一份JSON数据并生成条形图

    一.JSON 数据准备 首先准备一份 JSON 数据,这份数据共有 3560 条内容,每条内容结构如下: 本示例主要是以 tz(timezone 时区) 这一字段的值,分析这份数据里时区的分布情况. ...

  3. Linux下的解压命令小结

    Linux下常见的压缩包格式有5种:zip tar.gz tar.bz2 tar.xz tar.Z 其中tar是种打包格式,gz和bz2等后缀才是指代压缩方式:gzip和bzip2 filename. ...

  4. gRPC源码分析0-导读

    gRPC是Google开源的新一代RPC框架,官网是http://www.grpc.io.正式发布于2016年8月,技术栈非常的新,基于HTTP/2,netty4.1,proto3.虽然目前在工程化方 ...

  5. 初识Git

    Git是目前世界上最先进的分布式版本控制系统.在Git诞生之前,我们一直使用的是集中式版本控制系统(如CVS.SVN等),那么两者有什么不同呢?分布式的优势又在哪里呢? 分布式vs集中式 集中式版本控 ...

  6. JS实现文字截取(雾)

    今天在跳板群那里看到一个神奇的样式,效果: 感觉十分神奇,因为一开始以为他是只有一个P元素包着文字然后最后一个自动截取文字,而且最后一行还可以提前截取???这怎么做到的,然后想了一下css怎么做,好像 ...

  7. SharePoint 部署时报错: 未能提取此解决方案中的cab文件

    在vs里右击SharePoint项目,选择"部署",结果报错: Error occurred in deployment step 'Add Solution':Fail to e ...

  8. React Native知识10-ListView组件

    ListView - 一个核心组件,用于高效地显示一个可以垂直滚动的变化的数据列表.最基本的使用方式就是创建一个ListView.DataSource数据源,然后给它传递一个普通的数据数组,再使用数据 ...

  9. iOS加密方式及解压缩文件

    Base64加密方式 Base64是一种加密方法,可逆的加密. Base64中的可打印字符包括字母A-Z.a-z.数字0-9,这样共有62个字符./ + 填充 = echo -n BC|base64 ...

  10. MySql提示:The server quit without updating PID file(…)失败

    一般有一下集中可能 1.可能是/usr/local/mysql/data/rekfan.pid文件没有写的权限解决方法 :给予权限,执行 "chown -R mysql:mysql /var ...