给你一个由 ‘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
示例 2:
输入: grid = [
[“1”,“1”,“0”,“0”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“1”,“0”,“0”],
[“0”,“0”,“0”,“1”,“1”]
]
输出: 3
提示:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] 的值为 ‘0’ 或 ‘1’
注:
在遇到1就立刻置为0,不要等着从队列or栈中取出来之后再置为0,会导致大量坐标点被重复入队or入栈,使得时间超出限制!!!
##广度优先遍历
class Solution(object):
def numIslands(self, grid):
n = len(grid)#获取数组长度
if n == 0:
return 0
m = len(grid[0])#获取数组宽度
cnt = 0#岛屿数量
queue = []#队列容器
for i in range(n):
for j in range(m):
if grid[i][j] == "1":#如果遇见陆地就开始遍历
cnt+=1#岛屿数量加一
grid[i][j]="0"#置为0,以免重复访问
queue.append((i,j))#加入队列中,开始遍历
while queue:
x,y = queue[0]
queue.pop(0)
for xx,yy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:#四个方向遍历
if 0<=xx<n and 0<=yy<m and grid[xx][yy]=="1":
grid[xx][yy]="0"
queue.append((xx,yy))
return cnt
##深度优先遍历
class Solution(object):
def numIslands(self, grid):
n = len(grid)
if n == 0:
return 0
m = len(grid[0])
cnt = 0
stack = []
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
cnt+=1
grid[i][j]="0"
stack.insert(0,(i,j))
while stack:
x,y = stack[0]
stack.pop(0)
for xx,yy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if 0<=xx<n and 0<=yy<m and grid[xx][yy]=="1":
grid[xx][yy]="0"
stack.insert(0,(xx,yy))
return cnt