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