0
点赞
收藏
分享

微信扫一扫

【Leetcode】每日一题:太平洋大西洋水流问题

太平洋大西洋水流问题

AC代码

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        m = len(heights)
        n = len(heights[0])
        def getavail(inputs):
            avail = set()
            def dfs(x, y):
                if (x, y) in avail:
                    return
                avail.add((x, y))
                for nx, ny in [(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]:
                    if 0 <= nx < m and 0 <= ny < n and heights[x][y] <= heights[nx][ny]:
                        dfs(nx, ny)

            for x, y in inputs:
                dfs(x, y)
            return avail
        
        p = [(0, i) for i in range(n)] + [(j, 0) for j in range(1, m)]
        a = [(m - 1, i) for i in range(n)] + [(j, n - 1) for j in range(m - 1)]
        return list(map(list, getavail(p) & getavail(a)))

官方代码

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        m, n = len(heights), len(heights[0])

        def search(starts: List[Tuple[int, int]]) -> Set[Tuple[int, int]]:
            visited = set()
            def dfs(x: int, y: int):
                if (x, y) in visited:
                    return
                visited.add((x, y))
                for nx, ny in ((x, y + 1), (x, y - 1), (x - 1, y), (x + 1, y)):
                    if 0 <= nx < m and 0 <= ny < n and heights[nx][ny] >= heights[x][y]:
                        dfs(nx, ny)
            for x, y in starts:
                dfs(x, y)
            return visited

        pacific = [(0, i) for i in range(n)] + [(i, 0) for i in range(1, m)]
        atlantic = [(m - 1, i) for i in range(n)] + [(i, n - 1) for i in range(m - 1)]
        return list(map(list, search(pacific) & search(atlantic)))

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/pacific-atlantic-water-flow/solution/tai-ping-yang-da-xi-yang-shui-liu-wen-ti-sjk3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

1、最开始遍历有点想不明白,总觉得会有问题,这种从已成立的点开始遍历是个不会有问题的遍历方法

举报

相关推荐

0 条评论