class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid: return 0
m=len(grid)
n=len(grid[0])
directions=[(0,1),(1,0),(0,-1),(-1,0)]
def dfs(i,j):
grid[i][j]='0'
for direction in directions:
x,y=i+direction[0],j+direction[1]
if x<0 or x>m-1 or y<0 or y>n-1 or grid[x][y]=='0':
continue
dfs(x,y)
count=0
for i in xrange(m):
for j in xrange(n):
if grid[i][j]=='1':
count+=1
dfs(i,j)
return count
网友评论