# leetcode岛屿数量(200)-BFS

["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]

``Class Solution:def numIslands(self, grid):count=0for 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``

##### 一闪一闪

7 声望

1 粉丝

0 条评论

["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]

``Class Solution:def numIslands(self, grid):count=0for 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``