Changchun Master Li

leetcode 417. Pacific Atlantic Water Flow

2017-05-04

leetcode

首先想到让每个cell保存相邻cell信息, 然后利用回调来更新, 代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class MarixCallBack():
def __init__(self, matrix, size, triger):
self._triger = triger
self._row, self._col = size

self._matri = matrix
self._directions = [(1,0),(-1,0),(0,1),(0,-1)]

self._funcs = dict()
self._flags = set()

for i in range(self._row):
for j in range(self._col):
self._funcs[(i, j)] = set()

def Add(self, coordinate):
x, y = coordinate
if x == self._triger[0] or y == self._triger[1]:
self.Set(coordinate)
return

for direction in self._directions:
_x = x + direction[0]
_y = y + direction[1]
if _x > -1 and _x < self._row and _y > -1 and _y < self._col \
and self._matri[_x][_y] <= self._matri[x][y]:
if (_x, _y) in self._flags:
self.Set(coordinate)
return
else:
'''when shift has value, then call origin coordinate'''
self._funcs[(_x, _y)].add(coordinate)

def Set(self, coordinate):
if coordinate in self._flags:
return
self._flags.add(coordinate)
while self._funcs[coordinate]:
self.Set(self._funcs[coordinate].pop())

class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
m = len(matrix)
if m == 0:
return []
n = len(matrix[0])

PA = MarixCallBack(matrix, (m, n), (0, 0))
AT = MarixCallBack(matrix, (m, n), (m-1, n-1))

for i in range(m):
for j in range(n):
PA.Add((i, j))
AT.Add((i, j))

return list(AT._flags & PA._flags)

但需要遍历每一个节点, 虽然容易理解, 但是大矩阵复杂度较高.

所以最好从边缘dfs深度优先遍历每一个邻居

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class MarixDeepFirstSearch():
def __init__(self, matrix, size):
self._row, self._col = size
self._matri = matrix
self._directions = [(1,0),(-1,0),(0,1),(0,-1)]
self._added = set()

def Add(self, coordinate):
self._added.add(coordinate)
x, y = coordinate
for direction in self._directions:
_x = x + direction[0]
_y = y + direction[1]
if _x > -1 and _x < self._row and _y > -1 and _y < self._col \
and self._matri[_x][_y] >= self._matri[x][y] \
and (_x, _y) not in self._added:
'''Add larger coordinate'''
self.Add((_x, _y))

class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return []

m, n = len(matrix), len(matrix[0])
PA = MarixDeepFirstSearch(matrix, (m,n))
AT = MarixDeepFirstSearch(matrix, (m,n))

for i in range(m):
PA.Add((i, 0))
AT.Add((i, n-1))
for j in range(n):
PA.Add((0, j))
AT.Add((m-1, j))

return list(PA._added & AT._added)
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章