Skip to content

Latest commit

 

History

History
120 lines (61 loc) · 2.91 KB

0417._Pacific_Atlantic_Water_Flow.md

File metadata and controls

120 lines (61 loc) · 2.91 KB

417. Pacific Atlantic Water Flow

难度: Medium

刷题内容

原题连接

内容描述

Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:

Given the following 5x5 matrix:

  Pacific ~   ~   ~   ~   ~ 
       ~  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  *
          *   *   *   *   * Atlantic

Return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).

解题方案

思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(1)******

一上来本来打算对每一个点做一个dfs然后看看是否能够到达pacific和atlantic,然后将所有满足要求的点都加到res中去,后面一想这样会太慢了

于是看到了一个规律就是我们初始的时候总有第一行和第一列的所有点可以到达pacific,然后我们按照水往低处流的反方向去想(即河水倒流), 这样就可以得到所有能够到达pacific的点了,然后对于atlantic的初始点就是最后一行和最后一列

最后取他们的交集即可

beats 74.21%

class Solution:
    def pacificAtlantic(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        row = len(matrix)
        col = len(matrix[0]) if row else 0
        if not row:
            return []
        
        def dfs(start_points):
            stack = [point for point in start_points]
            reachable = start_points
            visited = set()
            while stack:
                (i, j) = stack.pop()
                for nxt_i, nxt_j in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
                    if 0 <= nxt_i < row and 0 <= nxt_j < col:
                        if (nxt_i, nxt_j) not in visited and matrix[nxt_i][nxt_j] >= matrix[i][j]:
                            visited.add((nxt_i, nxt_j))
                            stack.append((nxt_i, nxt_j))
                            reachable.add((nxt_i, nxt_j))
            return reachable
        
        pacific = set([(i, 0) for i in range(row)] + [(0, j) for j  in range(1, col)])  
        atlantic = set([(i, col-1) for i in range(row)] + [(row-1, j) for j in range(col-1)])
        return list(dfs(pacific) & dfs(atlantic))