|
| 1 | +// 힌트를 받은 아이디어: 특정 칸에서 흘러내려가는 것이 아니라, 바다에서부터 거슬러 올라가는 것을 계산하면 어떨까? |
| 2 | + |
| 3 | +class Solution { |
| 4 | + func pacificAtlantic(_ heights: [[Int]]) -> [[Int]] { |
| 5 | + var result = [[Int]]() |
| 6 | + var pacificMap = Array(repeating: Array(repeating: false, count: heights[0].count), count: heights.count) |
| 7 | + var atlanticMap = Array(repeating: Array(repeating: false, count: heights[0].count), count: heights.count) |
| 8 | + |
| 9 | + for k in 0..<heights[0].count { |
| 10 | + traverse(heights, 0, k, 0, &pacificMap) |
| 11 | + } |
| 12 | + |
| 13 | + for l in 0..<heights.count { |
| 14 | + traverse(heights, l, 0, 0, &pacificMap) |
| 15 | + } |
| 16 | + |
| 17 | + for m in 0..<heights[0].count { |
| 18 | + traverse(heights, heights.count - 1, m, 0, &atlanticMap) |
| 19 | + } |
| 20 | + |
| 21 | + for n in 0..<heights.count { |
| 22 | + traverse(heights, n, heights[0].count - 1, 0, &atlanticMap) |
| 23 | + } |
| 24 | + |
| 25 | + for i in 0..<heights.count { |
| 26 | + for j in 0..<heights[i].count { |
| 27 | + if pacificMap[i][j] && atlanticMap[i][j] { |
| 28 | + result.append([i, j]) |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return result |
| 34 | + } |
| 35 | + |
| 36 | + func traverse(_ heights: [[Int]], _ row: Int, _ col: Int, _ previous: Int, _ reachabilities: inout [[Bool]]) { |
| 37 | + guard (0..<heights.count) ~= row && (0..<heights[0].count) ~= col else { return } |
| 38 | + |
| 39 | + guard heights[row][col] >= previous else { return } |
| 40 | + guard !reachabilities[row][col] else { return } |
| 41 | + |
| 42 | + reachabilities[row][col] = true |
| 43 | + |
| 44 | + traverse(heights, row - 1, col, heights[row][col], &reachabilities) |
| 45 | + traverse(heights, row + 1, col, heights[row][col], &reachabilities) |
| 46 | + traverse(heights, row, col - 1, heights[row][col], &reachabilities) |
| 47 | + traverse(heights, row, col + 1, heights[row][col], &reachabilities) |
| 48 | + } |
| 49 | +} |
0 commit comments