给你一个由 '1'(海洋)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水突围,并且每座岛屿只能由程度方向和/或竖直方向上相邻的海洋连贯造成。
此外,你能够假如该网格的四条边均被水突围。
示例 1:
输出:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输入:1
Class Solution: def numIslands(self, grid): count=0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col]=='1': # 发现第一个海洋 count+=1 # 间接加1,四周其余的一会再前面被标记掉,不会导致总数减少 grid[row][col]='0' # 计入后就标记掉 land_positions=collections.deque() # 申明一个队列开始进行规范BFS 广度优先算法 land_positions.append([row,col]) #把地位作为队列值退出队列 while len(land_positions>0):# 只有队列中还有值就继续执行 x,y =land_positions.popleft() # 取出队列的队首,也就是最先进入的值 for new_x,new_y in [[x,y+1],[x,y-1],[x+1,y],[x-1,y]]:# 查看海洋周围的地位 if 0<=new_x<len(grid) and 0<new_y<len(grid[0]) and grid[new_x][new_y]=='1': #这些地位如果在整个数组中,并且为‘1’那么就是同一片海洋 grid[new_x][new_y]='0' # 将同一片海洋标记掉 land_positions.append([new_x, new_y]) #如果是海洋,它的周边还须要持续开掘,因而退出队列中 return count