number of islands
错误点
- 没检查grid element是否为1,光想着边界检测和visited check了,总共是3个条件
- visited check时机?最好是在dfs外面,在dfs里面设为true
- 小错误:grid的值是字符
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def dfs(grid, visited, x, y):
m = len(grid)
n = len(grid[0])
visited[x*n+y]=True
dir = [[1,0],[0,1],[-1,0],[0,-1]]
for d in dir:
x1=x+d[0]
y1=y+d[1]
if x1<m and x1>=0 and y1<n and y1>=0 and
not visited[x1*n+y1] and grid[x1][y1]=='1':
dfs(grid, visited, x1, y1)
if not grid: return 0
m = len(grid)
n = len(grid[0])
count = 0
visited = [False]*(m*n)
for x in range(m):
for y in range(n):
if not visited[x*n+y] and grid[x][y]=='1':
count+=1
dfs(grid, visited, x, y)
return count