当前位置:网站首页>Number of islands
Number of islands
2022-04-23 09:11:00 【Boundless universe PY】
from collections import deque
# Parameters grid It's a 01 matrix
# Return value islands Is the number of 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]
# The main function
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(“ Input :”, generator)
print(“ Output :”, solution.numIslands(generator))
版权声明
本文为[Boundless universe PY]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230657123950.html
边栏推荐
- Idea package jar file
- 501. 二叉搜索树中的众数
- 错误: 找不到或无法加载主类
- ATSS(CVPR2020)
- To remember the composition ~ the pre order traversal of binary tree
- Employee probation application (Luzhou Laojiao)
- Play with binary tree (25 points)
- 论文阅读《Multi-View Depth Estimation by Fusing Single-View Depth Probability with Multi-View Geometry》
- Mini - exercice MySQL (seulement pour les débutants, pas pour les non - débutants)
- 调包求得每个样本的k个邻居
猜你喜欢
随机推荐
政务中台研究目的建设目标,建设意义,技术创新点,技术效果
Go language self-study series | golang structure as function parameter
RSA 加密解密签名验签
Pctp test experience sharing
653. Sum of two IV - input BST
Machine learning (VI) -- Bayesian classifier
node安装
L2-022 rearrange linked list (25 points) (map + structure simulation)
Node installation
Cross domain configuration error: when allowcredentials is true, allowedorigins cannot contain the special value "*“
Little girl walking
Open services in the bottom bar of idea
資源打包關系依賴樹
Introduction to matlab
L2-024 tribe (25 points) (and check the collection)
Notes on xctf questions
108. Convert an ordered array into a binary search tree
小女孩行走
js 原型链的深入
Concave hull acquisition method based on convex hull of point cloud