|
| 1 | +/* |
| 2 | +* input : grid represents the heights of island |
| 3 | +* output : coordinates where water flows to both pacific and atlantic |
| 4 | +* |
| 5 | +* example |
| 6 | +* |
| 7 | +* 2 2 2 1,1 >> 1,2 >> atlantic / 1,1 >> 0,1 >> pacific |
| 8 | +* 3 3 1 |
| 9 | +* 4 3 1 |
| 10 | +* |
| 11 | +* do dfs/bfs from the edge of grids. |
| 12 | +* if cell is checked from pacific and atlantic add to result |
| 13 | +* solution dfs from edges |
| 14 | +* tc : O(m*n) |
| 15 | +* sc : O(mn) |
| 16 | +* |
| 17 | +* */ |
| 18 | +class Solution { |
| 19 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 20 | + int m = heights.length; |
| 21 | + int n = heights[0].length; |
| 22 | + int[][] pacific = new int[m][n]; |
| 23 | + int[][] atlantic = new int[m][n]; |
| 24 | + |
| 25 | + for(int i = 0; i < m; i++) { |
| 26 | + dfsHelper(heights, pacific, i, 0); |
| 27 | + } |
| 28 | + for(int j = 1; j < n; j++) { |
| 29 | + dfsHelper(heights,pacific, 0, j); |
| 30 | + } |
| 31 | + for(int i =0; i < m; i++) { |
| 32 | + dfsHelper(heights,atlantic, i, n-1); |
| 33 | + } |
| 34 | + for(int j = 0; j < n-1; j++) { |
| 35 | + dfsHelper(heights, atlantic, m-1, j); |
| 36 | + } |
| 37 | + List<List<Integer>> ans = new ArrayList<>(); |
| 38 | + for(int i = 0; i < m; i++) { |
| 39 | + for(int j = 0; j < n; j++) { |
| 40 | + if(pacific[i][j] == 1 && atlantic[i][j] == 1) { |
| 41 | + ans.add(List.of(i, j)); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + return ans; |
| 46 | + } |
| 47 | + |
| 48 | + static int[][] directions = { |
| 49 | + {1, 0}, {-1, 0}, {0, 1}, {0, -1} |
| 50 | + }; |
| 51 | + |
| 52 | + void dfsHelper(int[][] board, int[][] visited, int x, int y) { |
| 53 | + if(visited[x][y] > 0) return; |
| 54 | + visited[x][y] += 1; |
| 55 | + for(int[] direction : directions) { |
| 56 | + int nx = x + direction[0]; |
| 57 | + int ny = y + direction[1]; |
| 58 | + if(nx < 0 || nx >=visited.length || ny < 0 || ny >= visited[0].length || visited[nx][ny] > 0 || board[nx][ny] < board[x][y]) continue; |
| 59 | + dfsHelper(board, visited, nx, ny); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments