Pacific Atlantic Water Flow

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.


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


Given the following 5x5 matrix:





Initialise list的时候,如果简单的用list = [[False*numer]*number]]

只会create shallow copy, 里面的list都是同一个list。不可以这么写,debug半天没发现这个问题。

正确的写法list = [[False for _ in range(number)] for _ in range(number)]

def pacificAtlantic(self, matrix):
if not matrix: return []
direction = [[-1,0], [0,1], [1,0], [0,-1]]
colLen = len(matrix)
rowLen = len(matrix[0])
canReachP = [[False for _ in range(rowLen)] for _ in range(colLen)]
canReachA = [[False for _ in range(rowLen)] for _ in range(colLen)]
ans = []