考察DFS, 难点在于要分别判断是否能到达两大洋及如何设置搜索起始位置
class Solution:
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
m=len(matrix)
if m==0: return []
n=len(matrix[0])
Pdp=[[False]*n for _ in range(m)]
Adp=[[False]*n for _ in range(m)]
for i in range(m):
self.dfs(Pdp,matrix,m,n,i,0)
self.dfs(Adp,matrix,m,n,i,n-1)
for j in range(n):
self.dfs(Pdp,matrix,m,n,0,j)
self.dfs(Adp,matrix,m,n,m-1,j)
res=[]
for i in range(m):
for j in range(n):
if Pdp[i][j] and Adp[i][j]:
res.append([i,j])
return res
def dfs(self,visit,matrix,m,n,x,y):
visit[x][y]=True
for dx,dy in zip((-1,0,1,0),(0,-1,0,1)):
nx,ny=x+dx,y+dy
if nx<0 or nx>=m or ny<0 or ny>=n or visit[nx][ny] or matrix[nx][ny]<matrix[x][y]:
continue
self.dfs(visit,matrix,m,n,nx,ny)