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.

Note:

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

Example:

Given the following 5x5 matrix:

分析:

与其从每个点开始找,不如从每个边上开始往上走,看能reach到那些地方。

一样的用DFS来解决。

知识点:

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 = []