题目描述
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
思路
这道题和剑指offer矩阵中的路径和机器人的运动范围类似,https://blog.csdn.net/m0_38098373/article/details/94023539
但不同的地方是:
深度优先遍历:已经访问过的节点不再访问,所有点仅访问一次。(本题是深度优先遍历)
回溯法:已经访问过的点可能再次访问,也可能存在没有被访问过的点。(矩阵中的路径,有回退)
Ps:学到了一个把方向先保存起来的一个方法,可以让代码简洁
class Solution(object):
def __init__(self):
self.direction=[(-1,0),(0,-1),(1,0),(0,1)]
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if len(grid)<=0:
return 0
rows=len(grid)
cols=len(grid[0])
mark=[[False]*cols for _ in range(rows)]
count=0
for row in range(rows):
for col in range(cols):
if not mark[row][col] and grid[row][col]=="1":
count+=1
self.islandcount(grid,row,col,rows,cols,mark)
return count
def islandcount(self,grid,row,col,rows,cols,mark):
mark[row][col]=True
for direction in self.direction:
new_row=row+direction[0]
new_col=col+direction[1]
if 0<=new_row<rows and 0<=new_col<cols and not mark[new_row][new_col] and grid[new_row][new_col]=="1":
self.islandcount(grid,new_row,new_col,rows,cols,mark)