|
| 1 | +class Solution { |
| 2 | + private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 3 | + |
| 4 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 5 | + int numRows = heights.length; |
| 6 | + int numCols = heights[0].length; |
| 7 | + Queue<int[]> pacificQueue = new LinkedList<>(); |
| 8 | + Queue<int[]> atlanticQueue = new LinkedList<>(); |
| 9 | + for (int i = 0; i < numRows; i++) { |
| 10 | + pacificQueue.add(new int[]{i, 0}); |
| 11 | + atlanticQueue.add(new int[]{i, numCols - 1}); |
| 12 | + } |
| 13 | + for (int i = 0; i < numCols; i++) { |
| 14 | + pacificQueue.add(new int[]{0, i}); |
| 15 | + atlanticQueue.add(new int[]{numRows - 1, i}); |
| 16 | + } |
| 17 | + boolean[][] pacificReachable = bfs(pacificQueue, heights); |
| 18 | + boolean[][] atlanticReachable = bfs(atlanticQueue, heights); |
| 19 | + List<List<Integer>> result = new ArrayList<>(); |
| 20 | + for (int i = 0; i < numRows; i++) { |
| 21 | + for (int j = 0; j < numCols; j++) { |
| 22 | + if (pacificReachable[i][j] && atlanticReachable[i][j]) { |
| 23 | + result.add(Arrays.asList(i, j)); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + return result; |
| 28 | + } |
| 29 | + |
| 30 | + private boolean[][] bfs(Queue<int[]> queue, int[][] heights) { |
| 31 | + int numRows = heights.length; |
| 32 | + int numCols = heights[0].length; |
| 33 | + boolean[][] reachable = new boolean[numRows][numCols]; |
| 34 | + while (!queue.isEmpty()) { |
| 35 | + int[] removed = queue.remove(); |
| 36 | + int x = removed[0]; |
| 37 | + int y = removed[1]; |
| 38 | + reachable[x][y] = true; |
| 39 | + for (int[] dir : DIRS) { |
| 40 | + int newX = x + dir[0]; |
| 41 | + int newY = y + dir[1]; |
| 42 | + if (newX < 0 || newY < 0 || newX >= numRows || newY >= numCols || reachable[newX][newY]) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + if (heights[newX][newY] >= heights[x][y]) { |
| 46 | + queue.add(new int[]{newX, newY}); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + return reachable; |
| 51 | + } |
| 52 | +} |
0 commit comments