题目描述
题目描述
这道题目一开始并没有思路去思考,看了题解之后才慢慢的理解这个的意思。相当于dfs的变体,类似于判断拓扑路径。
##代码实现
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row,col=len(grid),len(grid[0])
count=0
visited=[[False]*col for _ in range(row)]
directions=[[0,-1],[1,0],[0,1],[-1,0]]
def outrange(x,y):
if x<0 or x>=row or y<0 or y>=col:
return False
else:
return True
def dfs(x,y):
visited[x][y]=True
for dx,dy in directions:
newx,newy=x+dx,y+dy
if outrange(newx,newy) and not visited[newx][newy] and grid[newx][newy]=='1':
dfs(newx,newy)
for i in range(row):
for j in range(col):
if grid[i][j] =='1' and not visited[i][j]:
dfs(i,j)
count+=1
return count