200.岛屿数量
【LetMeFly】200.岛屿数量
力扣题目链接:https://leetcode.cn/problems/number-of-islands/
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 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
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
的值为'0'
或'1'
方法一:BFS
用广度优先搜索遍历一遍地图,遇到为'1'
的方块就从开始广搜,并把答案的“岛屿数量”+1
广搜过程中,把遍历到的岛屿标记为'2'
一些广搜题列表可参考广度优先搜索题解专题,该专题主要包括图的广搜和二叉树的广搜。
- 时间复杂度$O(nm)$,其中地图的大小为$n\times m$
- 空间复杂度$O(M)$,其中$M$是最大的岛屿面积
AC代码
C++
1 |
|
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/126400354
200.岛屿数量
https://blog.letmefly.xyz/2022/08/18/LeetCode 0200.岛屿数量/