Skip to content

Commit a5e742a

Browse files
committed
solve
1 parent c2408fb commit a5e742a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
// O(m*n) time / O(m*n) space
3+
func pacificAtlantic(_ heights: [[Int]]) -> [[Int]] {
4+
var result = [[Int]]()
5+
guard let first = heights.first else {
6+
return result
7+
}
8+
let m = heights.count
9+
let n = first.count
10+
11+
var goesPacific = Array(repeating: Array(repeating: false, count: n), count: m)
12+
var goesAtlantic = Array(repeating: Array(repeating: false, count: n), count: m)
13+
let directions = [(1,0), (-1,0), (0,1), (0,-1)]
14+
15+
func dfs(i: Int, j: Int, goes: inout [[Bool]]) {
16+
if goes[i][j] {
17+
return
18+
}
19+
goes[i][j] = true
20+
21+
for (di, dj) in directions {
22+
let ni = i + di
23+
let nj = j + dj
24+
if ni >= 0
25+
&& ni < m
26+
&& nj >= 0
27+
&& nj < n
28+
&& heights[ni][nj] >= heights[i][j] {
29+
dfs(i: ni, j: nj, goes: &goes)
30+
}
31+
}
32+
}
33+
34+
for i in 0..<m {
35+
dfs(i: i, j: 0, goes: &goesPacific)
36+
dfs(i: i, j: n-1, goes: &goesAtlantic)
37+
}
38+
39+
for j in 0..<n {
40+
dfs(i: 0, j: j, goes: &goesPacific )
41+
dfs(i: m-1, j: j, goes: &goesAtlantic )
42+
}
43+
44+
for i in 0..<m {
45+
for j in 0..<n {
46+
if goesPacific[i][j] && goesAtlantic[i][j] {
47+
result.append([i, j])
48+
}
49+
}
50+
}
51+
return result
52+
}
53+
}

0 commit comments

Comments
 (0)