给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/number-of-islands
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
方法一:深度优先搜索(DFS)
def search(grid,x,y):
grid[x][y] = '0'
nr = len(grid)
nc = len(grid[0])
for i,j in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]:
if 0<= i < nr and 0<=j int:
nr = len(grid)
if nr == 0:
return 0
nc = len(grid[0])
flag = 0
for i in range(nr):
for j in range(nc):
if grid[i][j] == '1':
grid = search(grid,i,j)
flag += 1
return flag
方法二:广度优先搜索(BFS)
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
nr = len(grid)
if nr == 0:
return 0
nc = len(grid[0])
flag = 0
for i in range(nr):
for j in range(nc):
if grid[i][j] == '1':
flag += 1
grid[i][j] = '0'
neigh = [(i,j)]
while neigh:
m,n = neigh.pop(0)
for x,y in [(m+1,n),(m-1,n),(m,n+1),(m,n-1)]:
if 0<=x<nr and 0<=y<nc and grid[x][y] == '1':
grid[x][y] = '0'
neigh.append((x,y))
return flag