leetcode 417. Pacific Atlantic Water Flow (Python)

Leetcode 417. Pacific Atlantic Water Flow (Python)

Related Topic

Depth-First-Search. Graph.

Description

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.

Sample I/O

Example 1

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).

None

  1. The order of returned grid coordinates does not matter.
  2. Both m and n are less than 150.

Methodology

This question can be solved by Depth First Search.

We want to find the list of coordinates where water can flow both p and a. We can try to find all coordinates that flow to P and all coordinates that flow to A. The intersections of two list coordinates will be the coordinates that can flow both P and A.

Code(DFS)

def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
        if not matrix or not matrix[0]:return []
        m, n = len(matrix),len(matrix[0])
        p_visited = set()
        a_visited = set()
        directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
        def dfs(visited, x,y):
            visited.add((x,y))
            for dx, dy in directions:
                new_x, new_y = x+dx, y+dy
                if 0<=new_x<m and 0<=new_y<n and (new_x,new_y) not in visited and matrix[new_x][new_y]>=matrix[x][y]:
                    dfs(visited, new_x,new_y)
        #iterate from left border and right border
        for i in range(m):
            dfs(p_visited,i,0)
            dfs(a_visited,i,n-1)
        #iterate from up border and bottom border
        for j in range(n):
            dfs(p_visited,0,j)
            dfs(a_visited,m-1,j)
        #The intersections of two sets are coordinates where water can flow to both P and A
        return list(p_visited.intersection(a_visited))

BigO

We traversal all elements of the matrix once plus intersection so time complexity is O(2mn)

Search

    Table of Contents