[LeetCode] 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.
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 Connected Components in an Undirected Graph
参考资料:
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 岛屿的数量的更多相关文章
- [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 ...
- [LintCode] Number of Islands 岛屿的数量
Given a boolean 2D matrix, find the number of islands. Notice 0 is represented as the sea, 1 is repr ...
- LeetCode Number of Islands 岛的数量(DFS,BFS)
题意:0代表水,1代表陆地,那么被水围起来的就是岛了,给一个01矩阵,问有多少个岛? 思路:DFS还是比较短,实现了一下.如果一个点已经被遍历过了,那就将其置为0就行了,不要去搜0的. class S ...
- [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 ...
- 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 ...
- 【LeetCode】200. Number of Islands 岛屿数量
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...
- [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 ...
- [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 ...
- 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 ...
随机推荐
- js判断本机是否已安装app
需求:在浏览器或者app webview中打开的页面,js判断本机是否已安装搜狐新闻客户端. 一.微信 1.分享——好友/朋友圈,feed会有搜狐新闻标记,打开url后缀参数isappinstalle ...
- Federated Identity Pattern 联合身份模式
Delegate authentication to an external identity provider. This pattern can simplify development, min ...
- Angular 基础入门
简介 什么是AngularJS 一个功能非常完备的前端框架,通过增强HTML的方式提供一种便捷开发Web应用程序的方式 其核心特点就是几乎无任何DOM操作,让开发人员的精力和时间全部集中于业务 MVC ...
- CSS布局 - 三栏布局
CSS布局技术可谓是前端技术中最基础的技术,就是因为基础,所以我认为要更加熟练,深入的去掌握,去梳理. 一. 传统 ---> 浮动实现的三栏布局 采用浮动实现的三栏布局有以下特点及注意事项: · ...
- React-Native学习系列(一)
近段时间一直在忙,所以博客也没有更新,这两天我翻了一下写的这几篇博客,感觉写的都很片面,所以,我想重新写一个系列教程,从最基础的开始,来让大家更容易学会React-Native. 这个系列大部分只介绍 ...
- 和Java相关的书籍,想成为架构师的请收藏一下啊
1.<<Effective Java 中文第二版>> 2.<<Java并发编程实践>> 3.<<Java核心技术(原书第8版)卷I_基础知识 ...
- mongo DB for C#
(1)Download the MongoDB C#驱动. http://www.nuget.org/packages/mongocsharpdriver/. (2) Add Reference to ...
- Mac OS X搭建C#开发环境
在Mac下想要用C#语言的话,首先得有个跨平台的.Net环境-Mono http://www.mono-project.com/ 有了Mono平台之后,还得有一个好工具:目前比较好的IDE是Xmari ...
- thinkphp怎么修改配置进入默认首页
thinkphp文件夹下config 里面有个convention.php文件 里面有三个配置 'DEFAULT_MODULE' => 'Home', // 默认模块 'DEFAULT_CONT ...
- sessionStorage 和 localStorage 、cookie
sessionStorage 和 localStorage html5中web storage包括两种储存方式:sessionStorage 和 localStorage sessionStorage ...