Skip to content

Commit 54aee8d

Browse files
authored
pacific atlantic water flow solution
1 parent fe9408a commit 54aee8d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
object Solution {
2+
val _DRCS = Array(
3+
Array(-1, 0),
4+
Array(0, -1),
5+
Array(0, 1),
6+
Array(1, 0),
7+
)
8+
def pacificAtlantic(heights: Array[Array[Int]]): List[List[Int]] = {
9+
val visited = Array.fill[Array[Int]](heights.length)(
10+
Array.fill[Int](heights.head.length)(0)
11+
)
12+
for (i <- heights.indices) {
13+
dfs(heights, visited, i, 0, 1)
14+
dfs(heights, visited, i, heights.head.length - 1, 2)
15+
}
16+
for (i <- heights.head.indices) {
17+
dfs(heights, visited, 0, i, 1)
18+
dfs(heights, visited, heights.length - 1, i, 2)
19+
}
20+
(
21+
for {
22+
r <- visited.indices
23+
c <- visited.head.indices
24+
if visited(r)(c) == 3
25+
} yield List(r, c)
26+
).toList
27+
}
28+
def dfs(heights: Array[Array[Int]], visited: Array[Array[Int]], r: Int, c: Int, v: Int): Unit = {
29+
visited(r)(c) |= v
30+
_DRCS.map { case Array(dr, dc) => (r + dr, c + dc) }
31+
.filter { case (nr, nc) => nr != -1 && nr != heights.length && nc != -1 && nc != heights.head.length }
32+
.filter { case (nr, nc) => (visited(nr)(nc) & v) == 0 && heights(r)(c) <= heights(nr)(nc) }
33+
.foreach { case (nr, nc) =>
34+
dfs(heights, visited, nr, nc, v)
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)