当前位置:网站首页>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
边栏推荐
猜你喜欢

数据清洗 ETL 工具Kettle的安装

Emuelec compilation summary

To remember the composition ~ the pre order traversal of binary tree

Production practice elk

Flink SQL realizes the integration of stream and batch

653. Sum of two IV - input BST

108. 将有序数组转换为二叉搜索树

GoLand debug go use - white record

Mini - exercice MySQL (seulement pour les débutants, pas pour les non - débutants)

Harbor enterprise image management system
随机推荐
Download and install bashdb
基于ThinkPHP5版本TRC20-资金归集解决方案
Flink同时读取mysql与pgsql程序会卡住且没有日志
Leetcode-199 - right view of binary tree
Taxable income
What is augmented reality technology? Where can it be used?
Concave hull acquisition method based on convex hull of point cloud
[58] length of the last word [leetcode]
[C language] document operation
L2-022 重排链表 (25 分)(map+结构体模拟)
Experimental report on analysis of overflow vulnerability of assembly language and reverse engineering stack
Use include in databinding
OpenCV中的图像处理 —— 轮廓入门+轮廓特征
Technological innovation in government affairs in the construction of Digital Government
Summary of solid problems
Program, process, thread; Memory structure diagram; Thread creation and startup; Common methods of thread
[indexof] [lastIndexOf] [split] [substring] usage details
Failed to prepare device for development
Play with binary tree (25 points)
108. 将有序数组转换为二叉搜索树