1.第一次不知道为啥执行错误,本地运行大数据迭代深度超过
2.check的时候忘记检查=1
3.有特殊情况的,必须上下左右都检查一遍
4.python数组有负数这个比较特殊
35min
class Solution:
def __init__(self):
self.cnt=0
def numIslands(self, grid: List[List[str]]) -> int:
if not grid or len(grid)==0:return 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]=='1':
self.cnt+=1
self.dfs(grid,i,j)
return self.cnt
def dfs(self,grid: List[List[str]],i:int,j:int):
if self.check_valid(grid,i,j):
grid[i][j]=None
self.dfs(grid,i,j+1)
self.dfs(grid,i,j-1)
self.dfs(grid,i-1,j)
self.dfs(grid,i+1,j)
def check_valid(self,grid: List[List[str]],i:int,j:int):
try:
if i>=0 and i<len(grid) and j>=0 and j<len(grid[0]) and grid[i][j]!=None and grid[i][j]=='1':return True 记住python负数也可以使用,往下走的时候忘记判断==1
else:return False
except:
return False
网友评论