【宽度优先搜索 BFS】Leecode-200. 岛屿数量
【摘要】 【题目】给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。此外,你可以假设该网格的四条边均被水包围。 示例 1:输入:grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"],...
【题目】
给你一个由 '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
【题解】
题解1:
- 思路
列出可能的树形图,对于给出的列表逐个遍历调用dfs
- 复杂度
时间复杂度:O(n2),空间复杂度:O(n)
- 代码
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return []
m = len(grid)
n = len(grid[0])
def bfs(grid, i, j):
queue = [[i,j]]
while queue:
[i,j] = queue.pop(0)
if 0<=i<m and 0<=j<n and grid[i][j]=='1':
grid[i][j] = '0'
queue.extend([[i+1, j], [i-1,j], [i,j+1], [i, j-1]])
count=0
for i in range(m):
for j in range(n):
if grid[i][j] == '0':
continue
bfs(grid, i, j)
count += 1
return count
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)