Skip to content

Commit 24b0d1f

Browse files
committed
Create 0417-pacific-atlantic-water-flow.swift
1 parent 9800d75 commit 24b0d1f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
func pacificAtlantic(_ heights: [[Int]]) -> [[Int]] {
3+
let rows = heights.count
4+
let cols = heights[0].count
5+
var pac = Set<[Int]>()
6+
var atl = Set<[Int]>()
7+
var res = [[Int]]()
8+
9+
func dfs(_ r: Int, _ c: Int, _ visit: inout Set<[Int]>, _ prevHeight: Int) {
10+
if r < 0 || c < 0 || r == rows || c == cols || visit.contains([r, c]) || heights[r][c] < prevHeight {
11+
return
12+
}
13+
visit.insert([r, c])
14+
dfs(r + 1, c, &visit, heights[r][c])
15+
dfs(r - 1, c, &visit, heights[r][c])
16+
dfs(r, c + 1, &visit, heights[r][c])
17+
dfs(r, c - 1, &visit, heights[r][c])
18+
}
19+
20+
for c in 0..<cols {
21+
dfs(0, c, &pac, heights[0][c])
22+
dfs(rows - 1, c, &atl, heights[rows - 1][c])
23+
}
24+
25+
for r in 0..<rows {
26+
dfs(r, 0, &pac, heights[r][0])
27+
dfs(r, cols - 1, &atl, heights[r][cols - 1])
28+
}
29+
30+
for r in 0..<rows {
31+
for c in 0..<cols {
32+
if pac.contains([r, c]) && atl.contains([r, c]) {
33+
res.append([r, c])
34+
}
35+
}
36+
}
37+
38+
return res
39+
}
40+
}

0 commit comments

Comments
 (0)