给定一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入: 11110 11010 11000 00000 输出: 1
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
dindex = [(-1,0),(1,0),(0,-1),(0,1)]
end1 = len(grid)
end2 = len(grid[0])
count = 0
for i in range(end1):
for j in range(end2):
if grid[i][j] == '1':
count = count + 1
process = []
process.append((i,j))
while(process):
length = len(process)
for k in range(length):
index_y,index_x = process.pop()
grid[index_y][index_x] = '0'
for dx,dy in dindex:
y = index_y + dy
x = index_x + dx
if 0<= y <end1 and 0 <=x< end2 and grid[y][x] == '1':
process.append((y,x))
return count
之前在数据结构与算法这门课的OJ上老师留过这道题,自己就是直接的BFS 虽然效率很烂!!@@