|
| 1 | +/** |
| 2 | + * <a href="https://leetcode.com/problems/pacific-atlantic-water-flow/">week9-2. pacific-atlantic-water-flow</a> |
| 3 | + * <li>Description: Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. </li> |
| 4 | + * <li>Topics: Array, Depth-First Search, Breadth-First Search, Matrix</li> |
| 5 | + * <li>Time Complexity: O(MN), Runtime 9ms </li> |
| 6 | + * <li>Space Complexity: O(MN), Memory 45.18MB</li> |
| 7 | + */ |
| 8 | +class Solution { |
| 9 | + private int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 10 | + |
| 11 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 12 | + int m = heights.length; |
| 13 | + int n = heights[0].length; |
| 14 | + |
| 15 | + Queue<int[]> pacificQueue = new LinkedList<>(); |
| 16 | + boolean[][] pacific = new boolean[m][n]; |
| 17 | + for (int i = 0; i < m; i++) { |
| 18 | + pacific[i][0] = true; |
| 19 | + pacificQueue.offer(new int[]{i, 0}); |
| 20 | + } |
| 21 | + for (int i = 0; i < n; i++) { |
| 22 | + pacific[0][i] = true; |
| 23 | + pacificQueue.offer(new int[]{0, i}); |
| 24 | + } |
| 25 | + bfs(heights, pacificQueue, pacific); |
| 26 | + |
| 27 | + Queue<int[]> atlanticQueue = new LinkedList<>(); |
| 28 | + boolean[][] atlantic = new boolean[m][n]; |
| 29 | + for (int i = 0; i < m; i++) { |
| 30 | + atlantic[i][n - 1] = true; |
| 31 | + atlanticQueue.offer(new int[]{i, n - 1}); |
| 32 | + } |
| 33 | + for (int i = 0; i < n; i++) { |
| 34 | + atlantic[m - 1][i] = true; |
| 35 | + atlanticQueue.offer(new int[]{m - 1, i}); |
| 36 | + } |
| 37 | + bfs(heights, atlanticQueue, atlantic); |
| 38 | + |
| 39 | + List<List<Integer>> result = new ArrayList<>(); |
| 40 | + for (int i = 0; i < m; i++) { |
| 41 | + for (int j = 0; j < n; j++) { |
| 42 | + if (pacific[i][j] && atlantic[i][j]) { |
| 43 | + result.add(List.of(i, j)); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return result; |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + private void bfs(int[][] heights, Queue<int[]> queue, boolean[][] visit) { |
| 52 | + while (!queue.isEmpty()) { |
| 53 | + int[] curr = queue.poll(); |
| 54 | + int cr = curr[0]; |
| 55 | + int cc = curr[1]; |
| 56 | + |
| 57 | + for (int[] dir : directions) { |
| 58 | + int nr = cr + dir[0]; |
| 59 | + int nc = cc + dir[1]; |
| 60 | + |
| 61 | + if (nr < 0 || nr > heights.length - 1 || nc < 0 || nc > heights[0].length - 1 || visit[nr][nc]) { |
| 62 | + continue; |
| 63 | + } |
| 64 | + if (heights[nr][nc] >= heights[cr][cc]) { |
| 65 | + visit[nr][nc] = true; |
| 66 | + queue.offer(new int[]{nr, nc}); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments