当前位置:网站首页>岛屿的个数
岛屿的个数
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
边栏推荐
- 三星,再次“西征”
- 云计算技能大赛 -- openstack私有云环境 第二部分
- Move layout (Flex layout, viewport label)
- LeetCode15. 三数之和
- The displayed amount of ABAP ALV is inconsistent with the exported amount
- PHP high precision computing
- Convert object to URL
- Thinkphp6 + JWT realizes login verification
- Go语学习笔记 - Slice、Map | 从零开始Go语言
- BUUCTF [极客大挑战 2019]EasySQL1
猜你喜欢
随机推荐
Summary of facial classics
NIH降血脂指南《your guide to lowering your Cholesterol with TLC》笔记(持续更新中)
在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)
Redis transaction implements optimistic locking principle
3C装配中的机械臂运动规划
Distributed service governance Nacos
浏览器中的 Kubernetes 和 IDE | 交互式学习平台Killercoda
Hump naming object
Guoji Beisheng openstack container cloud environment construction
Fibula dynamic programming
Ribbon start process
vivo,硬件安全的爱与雷霆
Usage of databinding
Redis--为什么字符串emstr的字符串长度是44字节上限?
Convert object to URL
[programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
Ignis公链的NFT生态发展:Unicorn.art的捐赠开发之路
干货!以点为形:可微分的泊松求解器
智能名片小程序名片详情页功能实现关键代码
Thinkphp6 + JWT realizes login verification