|
| 1 | +class Solution { |
| 2 | + int[][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}}; |
| 3 | + |
| 4 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 5 | + /** |
| 6 | + 1.2๊ฐ์ ocean ๋ชจ๋๋ก ๋๋ฌํ ์ ์๋ ์นธ๋ค์ ์ฐพ๋ ๋ฌธ์ |
| 7 | + 2.height ๋์ ๊ณณ -> ๋ฎ์ ๊ณณ์ผ๋ก ์ด๋ |
| 8 | + time, space: O(mn) |
| 9 | + */ |
| 10 | + int m = heights.length; |
| 11 | + int n = heights[0].length; |
| 12 | + boolean[][] pacific = new boolean[m][n]; |
| 13 | + boolean[][] atlantic = new boolean[m][n]; |
| 14 | + |
| 15 | + List<List<Integer>> answer = new ArrayList<>(); |
| 16 | + |
| 17 | + for(int i = 0; i < m; i++) { |
| 18 | + dfs(i, 0, m, n, heights, pacific); |
| 19 | + dfs(i, n-1, m, n, heights, atlantic); |
| 20 | + } |
| 21 | + for(int j = 0; j < n; j++) { |
| 22 | + dfs(0, j, m, n, heights, pacific); |
| 23 | + dfs(m-1, j, m, n, heights, atlantic); |
| 24 | + } |
| 25 | + |
| 26 | + for(int i = 0; i < m; i++) { |
| 27 | + for(int j = 0; j < n; j++) { |
| 28 | + if(pacific[i][j] && atlantic[i][j]) { |
| 29 | + answer.add(Arrays.asList(i,j)); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + return answer; |
| 34 | + } |
| 35 | + |
| 36 | + void dfs(int i, int j, int m, int n, int[][] heights, boolean[][] visited) { |
| 37 | + if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j]) { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + visited[i][j] = true; |
| 42 | + for(int[] d: dirs) { |
| 43 | + int nexti = i + d[0]; |
| 44 | + int nextj = j + d[1]; |
| 45 | + |
| 46 | + //๋ฒ์ ์ && ๋ฐฉ๋ฌธ ์ํ๊ณ && ๋์ด ์กฐ๊ฑด ๋ง์กฑํ๋ฉด ๋ค์ ๋ฃจํธ ํ์ |
| 47 | + if(nexti >= 0 && nexti < m && nextj >= 0 && nextj < n && !visited[nexti][nextj] && heights[nexti][nextj] >= heights[i][j]) { |
| 48 | + dfs(nexti, nextj, m, n, heights, visited); |
| 49 | + } |
| 50 | + |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments