|
| 1 | +# Complexity |
| 2 | +- Time Complexity: $O(R*C)$ |
| 3 | + - `heights`의 행과 열인 R과 C에 대해, 반복문과 DFS의 비용인 `R*C`가 발생한다. |
| 4 | +- Space Complexity: $O(R*C)$ |
| 5 | + - `heights`의 행과 열인 R과 C에 대해, 방문 여부를 기록하는 배열(`pacifics`, `atlantics`)의 크기 비용인 `R*C`가 발생한다. |
| 6 | + |
| 7 | +# Code |
| 8 | +```go |
| 9 | +var offsets = [][]int{ |
| 10 | + {1, 0}, |
| 11 | + {-1, 0}, |
| 12 | + {0, 1}, |
| 13 | + {0, -1}, |
| 14 | +} |
| 15 | + |
| 16 | +func update(i int, j int, heights [][]int, visited [][]bool) { |
| 17 | + visited[i][j] = true |
| 18 | + |
| 19 | + for _, offset := range offsets { |
| 20 | + ni, nj := i+offset[0], j+offset[1] |
| 21 | + |
| 22 | + if ni < 0 || ni >= len(visited) || nj < 0 || nj >= len(visited[0]) || visited[ni][nj] || heights[i][j] > heights[ni][nj] { |
| 23 | + continue |
| 24 | + } |
| 25 | + update(ni, nj, heights, visited) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +func pacificAtlantic(heights [][]int) [][]int { |
| 30 | + parcifics := make([][]bool, len(heights)) |
| 31 | + for i, _ := range parcifics { |
| 32 | + parcifics[i] = make([]bool, len(heights[0])) |
| 33 | + } |
| 34 | + atlantics := make([][]bool, len(heights)) |
| 35 | + for i, _ := range atlantics { |
| 36 | + atlantics[i] = make([]bool, len(heights[0])) |
| 37 | + } |
| 38 | + |
| 39 | + for i, _ := range heights { |
| 40 | + for j, _ := range heights[0] { |
| 41 | + if i == 0 || j == 0 { |
| 42 | + update(i, j, heights, parcifics) |
| 43 | + } |
| 44 | + if i == len(heights)-1 || j == len(heights[0])-1 { |
| 45 | + update(i, j, heights, atlantics) |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + boths := make([][]int, 0) |
| 50 | + for i, _ := range heights { |
| 51 | + for j, _ := range heights[0] { |
| 52 | + if !(parcifics[i][j] && atlantics[i][j]) { |
| 53 | + continue |
| 54 | + } |
| 55 | + boths = append(boths, []int{i, j}) |
| 56 | + } |
| 57 | + } |
| 58 | + return boths |
| 59 | +} |
| 60 | + |
| 61 | +``` |
0 commit comments