|
| 1 | +- ๋ฌธ์ : https://leetcode.com/problems/pacific-atlantic-water-flow/ |
| 2 | +- ํ์ด: https://algorithm.jonghoonpark.com/2024/03/03/leetcode-417 |
| 3 | + |
| 4 | +```java |
| 5 | +public class Solution { |
| 6 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 7 | + List<List<Integer>> result = new ArrayList<>(); |
| 8 | + |
| 9 | + for (int i = 0; i < heights.length; i++) { |
| 10 | + for (int j = 0; j < heights[0].length; j++) { |
| 11 | + System.out.printf("\n\ninit Flow : %d, %d\n", i, j); |
| 12 | + Flow flow = new Flow(); |
| 13 | + dfs(flow, heights, Integer.MAX_VALUE, i, j); |
| 14 | + if (flow.flowToAtlanticOcean && flow.flowToPacificOcean) { |
| 15 | + result.add(List.of(i, j)); |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + return result; |
| 21 | + } |
| 22 | + |
| 23 | + private void dfs(Flow flow, int[][] heights, int prev, int i, int j) { |
| 24 | + if (i == -1 || j == -1) { |
| 25 | + flow.flowToPacificOcean = true; |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + if (i == heights.length || j == heights[0].length) { |
| 30 | + flow.flowToAtlanticOcean = true; |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + if (heights[i][j] == -1 || heights[i][j] > prev || flow.flowToAtlanticOcean && flow.flowToPacificOcean) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + int currentHeight = heights[i][j]; |
| 39 | + heights[i][j] = -1; |
| 40 | + |
| 41 | + dfs(flow, heights, currentHeight, i + 1, j); |
| 42 | + dfs(flow, heights, currentHeight, i - 1, j); |
| 43 | + dfs(flow, heights, currentHeight, i, j + 1); |
| 44 | + dfs(flow, heights, currentHeight, i, j - 1); |
| 45 | + |
| 46 | + heights[i][j] = currentHeight; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class Flow { |
| 51 | + boolean flowToPacificOcean; |
| 52 | + boolean flowToAtlanticOcean; |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +## TC, SC |
| 57 | + |
| 58 | +heights์ ๊ธธ์ด๋ฅผ `w`, heights[0]์ ๊ธธ์ด๋ฅผ `h`๋ก ์ ์ํ์ ๋, |
| 59 | +์ด ์ฝ๋์ ์๊ฐ ๋ณต์ก๋๋ `O((w \* h)^2)`, ๊ณต๊ฐ ๋ณต์ก๋๋ `O(w \* h)` ์ด๋ค. |
| 60 | +์๊ฐ ๋ณต์ก๋๊ฐ ์ ๋ ๊ฒ ๋์จ ์ด์ ๋ ๋ชจ๋ ์ขํ์ ๋ํด์ dfs๋ฅผ ์งํํ๊ธฐ ๋๋ฌธ์ด๋ค. |
0 commit comments