其他分享
首页 > 其他分享> > 递归和回溯_leetcode-floodfill

递归和回溯_leetcode-floodfill

作者:互联网

class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""


self.res = 0
if not grid :
return self.res

self.drection = [[-1,0],[0,1],[1,0],[0,-1]]

self.m = len(grid)

self.n = len(grid[0])

self.visit = [[False for i in range(self.n)] for i in range(self.m)]

for x in range(self.m):
for y in range(self.n):
if grid[x][y] == "1" and self.visit[x][y] == False:

self.res += 1
self.dfs(grid,x,y)

return self.res

def inArea(self,x,y):
return x >= 0 and x < self.m and y >= 0 and y < self.n

def dfs(self,grid,x,y):

self.visit[x][y] = True

for item in self.drection:
newX = x + item[0]
newY = y + item[1]

if self.inArea(newX,newY) and self.visit[newX][newY] == False and grid[newX][newY] == "1":
self.dfs(grid,newX,newY)

return

标签:return,res,self,floodfill,newX,newY,grid,回溯,leetcode
来源: https://www.cnblogs.com/lux-ace/p/10557048.html