[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 ...
随机推荐
- STemwin汉字显示
硬件环境: STM32F429,电容屏800X480 5点触控RGB屏幕 ,SPI flash: 软件环境: UCOSIII,STemwin: 汉字显示方法: 1.在SPIflash中装在字库XBF_ ...
- 使用roslyn代替MSBuild完成解决方案编译
原本我是使用批处理调用 MSBuild 完成解决方案编译的,新版的 MSBuild 在 Visual Studio 2015 会自带安装. 当然在Visual Studio 2015 中,MSBuil ...
- 选择目录,选择文件夹的COM组件问题。在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。
异常: 在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式.请确保您的 Main 函数带有 STAThreadAttribute 标记. 只有将调试器附加到该进程才会引发此异常. ...
- Node.js写文件的三种方法
Node.js写文件的三种方式: 1.通过管道流写文件 采用管道传输二进制流,可以实现自动管理流,可写流不必当心可读流流的过快而崩溃,适合大小文件传输(推荐) var readStream = fs. ...
- c3p0连接数据库的3种方式
c3p0连接数据库的3种方式,这里以mysql为例 1. 直接用set方法设置参数, 基本方法 ComboPooledDataSource dataSource = new ComboPooledDa ...
- go-使用 unsafe 修改 struct 中的 field 的值
以下是方法,不要纠结原理,等东西积累多了,你才有能力纠结原理: 首先,你需要有一个这样的函数,这是在 nsq 的源码里直接抄过来的: func unsafeValueOf(val reflect.Va ...
- IT基础架构规划方案一(网络系统规划)
背景 某集团经过多年的经营,公司业务和规模在不断发展,公司管理层和IT部门也认识到通过信息化手段可以更好地支撑公司业务运营.提高企业生产和管理效率.同时随着新建办公 ...
- 9.2.3 .net core 通过TagHelper封装控件
.net core 除了继续保留.net framework的HtmlHelper的写法以外,还提供了TagHelper和ViewComponent方式生成控件. 我们本节说的是使用TagHelper ...
- JQuery中$.ajax()方法参数详解
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...
- Three.js制作360度全景图
这是个基于three.js的插件,预览地址:戳这里 使用方法: 1.这个插件的用法很简单,引入如下2个js <script src="js/three.min.js"> ...