200.岛屿数量
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
输入:
11000
11000
00100
00011
输出: 3
from queue import Queue
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
try:
r = 0
m = len(grid)
n = len(grid[0])
around = ((0, 1), (1, 0), (0, -1), (-1, 0))
except:
return 0
for i in range(m):
for j in range(n):
if int(grid[i][j]):
r += 1
# ---------------------------BFS 开始--------------------
# 把根节点投入队列
q = Queue()
q.put((i, j))
# 开始循环
while not q.empty():
# 取出还未沉没的陆地节点并沉没陆地(防止下次遍历到时再算一遍)
x, y = q.get()
if int(grid[x][y]):
grid[x][y] = '0'
# 放入周围的陆地节点
for a, b in around:
a += x
b += y
if 0 <= a < m and 0 <= b < n \
and int(grid[a][b]):
q.put((a, b))
# ------------------------------------------------------
return r