1. 题目
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/number-of-islands
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题思路
BFS遍历四个方向(上下左右);其中,先把所有是 1 的坐标记下,然后选取其中一个坐标进行bfs遍历与其相连的其他是 1 的坐标,直到遍历结束,此时,岛屿数量加1.再次取下一个是 1 的坐标,如果该坐标已经遍历过,则跳过。
(一开始按照数岛屿相连的数量的那个思路,从头到尾和从尾到头两次遍历来做,但是发现做不出!)
from collections import deque
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# bfs
queue = deque()
# start
found = False
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
start = (i,j)
found = True
queue.append(start)
if found:
queue.append(start)
visited = [[0 for j in range(len(grid[0]))] for i in range(len(grid))]
tmpqueue = deque()
size = len(queue)
cnt = 0
for k in range(size):
first = True
isIsland = False
while len(tmpqueue)>0 or first:
if first:
x,y = queue.popleft()
first = False
else:
x,y = tmpqueue.popleft()
if visited[x][y] == 1:
continue
else:
if not isIsland:
isIsland = True
visited[x][y] = 1
if x+1<len(grid):
if grid[x+1][y] == '1':
tmpqueue.append((x+1,y))
if y+1 <len(grid[0]):
if grid[x][y+1] == '1':
tmpqueue.append((x,y+1))
if x-1 >= 0:
if grid[x-1][y] == '1':
tmpqueue.append((x-1,y))
if y-1 >= 0:
if grid[x][y-1] == '1':
tmpqueue.append((x,y-1))
if isIsland:
cnt += 1
return cnt
重新写了一个BFS,思路一样,代码架构会更清晰:
from collections import deque
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
#bfs
if len(grid) == 0:
return 0
queue = deque()
num_island = 0
dx = [1,0,-1,0]
dy = [0,1,0,-1]
visited = set()
queue2 = deque()
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "1":
x,y = i,j
if (x, y) in visited:
continue
else:
visited.add((x,y))
num_island += 1
queue2.append((x,y))
while len(queue2) > 0:
x,y = queue2.popleft()
for k in range(4):
new_x = x+dx[k]
new_y = y+dy[k]
if new_x>=len(grid) or new_y>=len(grid[0]) or new_x<0 or new_y<0:
continue
if (new_x, new_y) not in visited:
visited.add((new_x,new_y))
if grid[new_x][new_y] == "1":
queue2.append((new_x,new_y))
return num_island