当前位置:网站首页>岛屿的个数
岛屿的个数
2022-04-23 06:57:00 【洪荒宇宙py】
from collections import deque
#参数grid是一个01矩阵
#返回值islands是岛屿的个数
class Solution:
def numIslands(self, grid):
if not grid or not grid[0]:
return 0
islands = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
self.bfs(grid, i, j)
islands += 1
return islands
def bfs(self, grid, x, y):
queue = deque([(x, y)])
grid[x][y] = False
while queue:
x, y = queue.popleft()
for delta_x, delta_y in [(1, 0), (0, -1), (-1, 0), (0, 1)]:
next_x = x + delta_x
next_y = y + delta_y
if not self.is_valid(grid, next_x, next_y):
continue
queue.append((next_x, next_y))
grid[next_x][next_y] = False
def is_valid(self, grid, x, y):
n, m = len(grid), len(grid[0])
return 0 <= x < n and 0 <= y < m and grid[x][y]
#主函数
if name == ‘main’:
generator= [
[1,1,1,1,2],
[0,1,0,0,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,0,0,1]
]
solution = Solution()
print(“输入:”, generator)
print(“输出:”, solution.numIslands(generator))
版权声明
本文为[洪荒宇宙py]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_56852291/article/details/124356426
边栏推荐
猜你喜欢
Cloud computing skills competition -- Part 2 of openstack private cloud environment
Cloud computing skills competition -- the first part of openstack private cloud environment
智能名片小程序名片详情页功能实现关键代码
Three minutes to teach you to use Houdini fluid > > to solve particle fluid droplets
Buctf MISC brossage
How does feign integrate hystrix
Go语学习笔记 - 异常处理 | 从零开始Go语言
yum源仓库本地搭建的两种方法
Go语学习笔记 - 数组 | 从零开始Go语言
三星,再次“西征”
随机推荐
Redis事务实现乐观锁原理
【编程实践/嵌入式比赛】嵌入式比赛学习记录(一):TCP服务器和web界面的建立
Intranet penetration series: icmptunnel of Intranet tunnel (Master James Barlow's)
Feign源码分析
Summary of facial classics
C语言学习记录——삼십팔 字符串函数使用和剖析(2)
Flutter之Provider共享数据的两种方式
国基北盛-openstack-容器云-环境搭建
3C裝配中的機械臂運動規劃
MySQL——第一章节(MySQL中的数据类型)
Go语学习笔记 - 异常处理 | 从零开始Go语言
Buuctf misc brush questions
MySQL -- the secret of lock -- how to lock data
PHP high precision computing
Buctf MISC brossage
【编程实践/嵌入式比赛】嵌入式比赛学习记录(二):基于TCP的图片流传输
yum源仓库本地搭建的两种方法
[problem solving] vs2019 solves the problem that the EXE file generated by compilation cannot be opened
Convert object to URL
Planification du mouvement du manipulateur dans l'assemblage 3c