|
| 1 | +public class sora0319 { |
| 2 | + public class Solution { |
| 3 | + private int[][] heights; |
| 4 | + private int rows, cols; |
| 5 | + |
| 6 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 7 | + this.heights = heights; |
| 8 | + this.rows = heights.length; |
| 9 | + this.cols = heights[0].length; |
| 10 | + List<List<Integer>> result = new ArrayList<>(); |
| 11 | + |
| 12 | + for (int row = 0; row < rows; row++) { |
| 13 | + for (int col = 0; col < cols; col++) { |
| 14 | + Set<String> visitedPac = new HashSet<>(); |
| 15 | + Set<String> visitedAtl = new HashSet<>(); |
| 16 | + |
| 17 | + if (dfsPac(row, col, visitedPac) && dfsAtl(row, col, visitedAtl)) { |
| 18 | + result.add(Arrays.asList(row, col)); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + return result; |
| 23 | + } |
| 24 | + |
| 25 | + private boolean dfsPac(int row, int col, Set<String> visited) { |
| 26 | + String key = row + "," + col; |
| 27 | + if (visited.contains(key)) return false; |
| 28 | + visited.add(key); |
| 29 | + |
| 30 | + if (row == 0 || col == 0) return true; |
| 31 | + |
| 32 | + int[][] moved = { {0, -1}, {0, 1}, {-1, 0}, {1, 0} }; |
| 33 | + for (int[] m : moved) { |
| 34 | + int r = row + m[0]; |
| 35 | + int c = col + m[1]; |
| 36 | + if (isRange(r, c) && heights[row][col] >= heights[r][c]) { |
| 37 | + if (dfsPac(r, c, visited)) return true; |
| 38 | + } |
| 39 | + } |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + private boolean dfsAtl(int row, int col, Set<String> visited) { |
| 44 | + String key = row + "," + col; |
| 45 | + if (visited.contains(key)) return false; |
| 46 | + visited.add(key); |
| 47 | + |
| 48 | + if (row == rows - 1 || col == cols - 1) return true; |
| 49 | + |
| 50 | + int[][] directions = { {0, -1}, {0, 1}, {-1, 0}, {1, 0} }; |
| 51 | + for (int[] dir : directions) { |
| 52 | + int r = row + dir[0]; |
| 53 | + int c = col + dir[1]; |
| 54 | + if (isRange(r, c) && heights[row][col] >= heights[r][c]) { |
| 55 | + if (dfsAtl(r, c, visited)) return true; |
| 56 | + } |
| 57 | + } |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + private boolean isRange(int r, int c) { |
| 62 | + return r >= 0 && r < rows && c >= 0 && c < cols; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
| 67 | + |
0 commit comments