|
| 1 | +// |
| 2 | +// 417. Pacific Atlantic Water Flow |
| 3 | +// https://leetcode.com/problems/pacific-atlantic-water-flow/description/ |
| 4 | +// Dale-Study |
| 5 | +// |
| 6 | +// Created by WhiteHyun on 2024/06/29. |
| 7 | +// |
| 8 | + |
| 9 | +class Solution { |
| 10 | + func pacificAtlantic(_ heights: [[Int]]) -> [[Int]] { |
| 11 | + var result: [[Int]] = [] |
| 12 | + for i in heights.indices { |
| 13 | + for j in heights[i].indices where isValid(i, j, heights) { |
| 14 | + result.append([i, j]) |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + return result |
| 19 | + } |
| 20 | + |
| 21 | + private func isValid(_ i: Int, _ j: Int, _ heights: [[Int]]) -> Bool { |
| 22 | + var visited: [[Bool]] = .init( |
| 23 | + repeating: .init(repeating: false, count: heights[i].count), |
| 24 | + count: heights.count |
| 25 | + ) |
| 26 | + visited[i][j] = true |
| 27 | + var pacificOceanFlag = i == 0 || j == 0 |
| 28 | + var atlanticOceanFlag = i == heights.count - 1 || j == heights[i].count - 1 |
| 29 | + |
| 30 | + func dfs(_ x: Int, _ y: Int) { |
| 31 | + if pacificOceanFlag, atlanticOceanFlag { return } |
| 32 | + for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { |
| 33 | + let nx = x + dx |
| 34 | + let ny = y + dy |
| 35 | + |
| 36 | + guard heights.indices ~= nx, |
| 37 | + heights[nx].indices ~= ny, |
| 38 | + visited[nx][ny] == false, |
| 39 | + heights[nx][ny] <= heights[x][y] |
| 40 | + else { |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + visited[nx][ny] = true |
| 45 | + if nx == 0 || ny == 0 { |
| 46 | + pacificOceanFlag = true |
| 47 | + } |
| 48 | + if nx == heights.endIndex - 1 || ny == heights[nx].endIndex - 1 { |
| 49 | + atlanticOceanFlag = true |
| 50 | + } |
| 51 | + |
| 52 | + dfs(nx, ny) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + dfs(i, j) |
| 57 | + |
| 58 | + return pacificOceanFlag && atlanticOceanFlag |
| 59 | + } |
| 60 | +} |
0 commit comments