当前位置:网站首页>岛屿的个数
岛屿的个数
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
边栏推荐
- SAP tr manual import system operation manual
- Attack and defense world misc questions 1-50
- Asynchronous learning
- Feign源码分析
- How does feign integrate hystrix
- 云计算赛项--2020年赛题基础部分[任务3]
- 使用 Ingress 实现金丝雀发布
- Chapter IV intangible assets
- NIH降血脂指南《your guide to lowering your Cholesterol with TLC》笔记(持续更新中)
- Redis--为什么字符串emstr的字符串长度是44字节上限?
猜你喜欢
随机推荐
以下程序实现从字符串str中删除第i个字符开始的连续n个字
简述CPU
每周leetcode - 06 数组专题 7~739~50~offer 62~26~189~9
Convert object to URL
学fpga(从verilog到hls)
Buctf MISC brossage
DVWA靶场练习
php生成短链接:将数字转成字母,将字母转成数字
Alibaba sentinel学习QA
upload-labs 靶场练习
PHP generates short links: convert numbers to letters and letters to numbers
国基北盛-openstack-容器云-环境搭建
Chapter IV intangible assets
Draw a circle quickly in MATLAB (the one that can be drawn directly given the coordinates and radius of the center of the circle)
Principle of sentinel integrating Nacos to update data dynamically
Redis事务实现乐观锁原理
Interview learning route
[极客大挑战 2019]Havefun1
[go] common concurrency model [generic version]
Asynchronous learning









