Skip to content

Commit 3810709

Browse files
committed
5.17
1 parent e13500e commit 3810709

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<p>Given an <code>m x n</code> 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.</p>
2+
3+
<p>Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.</p>
4+
5+
<p>Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.</p>
6+
7+
<p><b>Note:</b><br />
8+
<ol>
9+
<li>The order of returned grid coordinates does not matter.</li>
10+
<li>Both <i>m</i> and <i>n</i> are less than 150.</li>
11+
</ol>
12+
</p>
13+
<p><b>Example:</b>
14+
<pre>
15+
Given the following 5x5 matrix:
16+
17+
Pacific ~ ~ ~ ~ ~
18+
~ 1 2 2 3 (5) *
19+
~ 3 2 3 (4) (4) *
20+
~ 2 4 (5) 3 1 *
21+
~ (6) (7) 1 4 5 *
22+
~ (5) 1 1 2 4 *
23+
* * * * * Atlantic
24+
25+
Return:
26+
27+
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
28+
</pre>
29+
</p>
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Solution(object):
2+
def pacificAtlantic(self, matrix):
3+
"""
4+
:type matrix: List[List[int]]
5+
:rtype: List[List[int]]
6+
"""
7+
8+
if not matrix or not matrix[0]:
9+
return list()
10+
m, n = len(matrix), len(matrix[0])
11+
12+
po = [[0 for i in range(n)] for j in range(m)] #po[i][j] = 1就代表matrix[i][j]可以被太平洋的水流到
13+
ao = [[0 for i in range(n)] for j in range(m)] #同上,换成大西洋
14+
15+
16+
dx = [1, -1, 0, 0]
17+
dy = [0, 0, 1, -1]
18+
19+
def dfs(x0, y0, string):
20+
if visited[x0][y0] == 1:#来过了
21+
return
22+
visited[x0][y0] = 1
23+
24+
if string == "po":
25+
po[x0][y0] = 1
26+
else:
27+
ao[x0][y0] = 1
28+
29+
for k in range(4):
30+
x = x0 + dx[k]
31+
y = y0 + dy[k]
32+
33+
if 0<= x < m and 0 <= y < n and matrix[x][y] >= matrix[x0][y0]: #可以流到下一个点
34+
dfs(x, y, string)
35+
36+
visited = [[0 for i in range(n)] for j in range(m)]
37+
i = 0
38+
for j in range(n):
39+
dfs(i, j, "po") #上面的太平洋
40+
41+
visited = [[0 for i in range(n)] for j in range(m)]
42+
i = m - 1
43+
for j in range(n):
44+
dfs(i, j, "ao") #下面的大西洋
45+
46+
visited = [[0 for i in range(n)] for j in range(m)]
47+
j = 0
48+
for i in range(m):
49+
dfs(i, j, "po") #左边的太平洋
50+
51+
visited = [[0 for i in range(n)] for j in range(m)]
52+
j = n - 1
53+
for i in range(m):
54+
dfs(i, j, "ao") #右边的大西洋
55+
56+
res = []
57+
for i in range(m):
58+
for j in range(n):
59+
if po[i][j] and ao[i][j]: #取交集
60+
res.append([i, j])
61+
62+
return res

0 commit comments

Comments
 (0)