0
点赞
收藏
分享

微信扫一扫

417. Pacific Atlantic Water Flow刷题笔记

律楷粑粑 2022-04-05 阅读 20

问题描述
这个应该用深度优先,dfs
顺带学一下bfs,
第一次没写出来,参考的是这篇博客
LeetCode代码

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        if not heights or not heights[0]:
            return []
        Pacific = set()
        Atlantic = set()
        m = len(heights)
        n = len(heights[0])
        directions = [[-1,0],[1,0],[0,-1],[0,+1]]
        def dfs(OceanSet:set, x, y):
            OceanSet.add((x,y))
            for dx,dy in directions:
                ix = x+dx
                iy = y+dy
                if 0<=ix< m and 0<= iy < n and (ix,iy) not in OceanSet and heights[ix][iy]>=heights[x][y]:
                    dfs(OceanSet,ix,iy)
        for i in range(m):
            dfs(Pacific,i,0)
            dfs(Atlantic,i,n-1)
        for j in range(n):
            dfs(Pacific,0,j)
            dfs(Atlantic,m-1,j)
        return list(Pacific.intersection(Atlantic))

运行结果如下
在这里插入图片描述
pycharm代码

class Solution:
    def pacificAtlantic(self, heights):
        if not heights or not heights[0]:
            return []
        Pacific = set()
        Atlantic = set()
        m = len(heights)
        n = len(heights[0])
        directions = [[-1,0],[1,0],[0,-1],[0,+1]]
        def dfs(OceanSet:set, x, y):
            OceanSet.add((x,y))
            for dx,dy in directions:
                ix = x+dx
                iy = y+dy
                if 0<=ix< m and 0<= iy < n and (ix,iy) not in OceanSet and heights[ix][iy]>=heights[x][y]:
                    dfs(OceanSet,ix,iy)
        for i in range(m):
            dfs(Pacific,i,0)
            dfs(Atlantic,i,n-1)
        for j in range(n):
            dfs(Pacific,0,j)
            dfs(Atlantic,m-1,j)
        return list(Pacific.intersection(Atlantic))


heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
print(Solution().pacificAtlantic(heights))


举报

相关推荐

0 条评论