|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class `pacific-atlantic-water-flow` { |
| 7 | + |
| 8 | + private val dirs = listOf( |
| 9 | + intArrayOf(0, 1), |
| 10 | + intArrayOf(0, -1), |
| 11 | + intArrayOf(1, 0), |
| 12 | + intArrayOf(-1, 0) |
| 13 | + ) |
| 14 | + |
| 15 | + /** |
| 16 | + * TC: O(n * m), SC: O(n * m) |
| 17 | + */ |
| 18 | + fun pacificAtlantic(heights: Array<IntArray>): List<List<Int>> { |
| 19 | + val (row, col) = heights.size to heights.first().size |
| 20 | + val pacific = Array(row) { BooleanArray(col) } |
| 21 | + val atlantic = Array(row) { BooleanArray(col) } |
| 22 | + |
| 23 | + for (index in 0 until row) { |
| 24 | + dfs(heights, pacific, Int.MIN_VALUE, index, 0) |
| 25 | + dfs(heights, atlantic, Int.MIN_VALUE, index, col - 1) |
| 26 | + } |
| 27 | + |
| 28 | + for (index in 0 until col) { |
| 29 | + dfs(heights, pacific, Int.MIN_VALUE, 0, index) |
| 30 | + dfs(heights, atlantic, Int.MIN_VALUE, row - 1, index) |
| 31 | + } |
| 32 | + |
| 33 | + val result = mutableListOf<List<Int>>() |
| 34 | + for (i in 0 until row) { |
| 35 | + for (j in 0 until col) { |
| 36 | + if (pacific[i][j] && atlantic[i][j]) { |
| 37 | + result.add(listOf(i, j)) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return result |
| 42 | + } |
| 43 | + |
| 44 | + private fun dfs(heights: Array<IntArray>, visited: Array<BooleanArray>, height: Int, r: Int, c: Int) { |
| 45 | + val (row, col) = heights.size to heights.first().size |
| 46 | + if (r < 0 || r >= row || c < 0 || c >= col || visited[r][c] || heights[r][c] < height) |
| 47 | + return |
| 48 | + |
| 49 | + visited[r][c] = true |
| 50 | + for (dir in dirs) { |
| 51 | + dfs(heights, visited, heights[r][c], r + dir[0], c + dir[1]) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + fun `ํํ์๊ณผ ๋์์์ ๋ชจ๋ ํ๋ฅผ ์ ์๋ ์
์ ์์น๋ฅผ ๋ฐํํ๋ผ`() { |
| 57 | + pacificAtlantic( |
| 58 | + arrayOf( |
| 59 | + intArrayOf(1,2,2,3,5), |
| 60 | + intArrayOf(3,2,3,4,4), |
| 61 | + intArrayOf(2,4,5,3,1), |
| 62 | + intArrayOf(6,7,1,4,5), |
| 63 | + intArrayOf(5,1,1,2,4) |
| 64 | + ) |
| 65 | + ) shouldBe arrayOf( |
| 66 | + intArrayOf(0,4), |
| 67 | + intArrayOf(1,3), |
| 68 | + intArrayOf(1,4), |
| 69 | + intArrayOf(2,2), |
| 70 | + intArrayOf(3,0), |
| 71 | + intArrayOf(3,1), |
| 72 | + intArrayOf(4,0) |
| 73 | + ) |
| 74 | + } |
| 75 | +} |
0 commit comments