|
| 1 | +classSolution { |
| 2 | +privatefinalint[][]DIRS = {{1,0}, {0,1}, {-1,0}, {0, -1}}; |
| 3 | + |
| 4 | +publicList<List<Integer>>pacificAtlantic(int[][]heights) { |
| 5 | +intnumRows =heights.length; |
| 6 | +intnumCols =heights[0].length; |
| 7 | +Queue<int[]>pacificQueue =newLinkedList<>(); |
| 8 | +Queue<int[]>atlanticQueue =newLinkedList<>(); |
| 9 | +for (inti =0;i <numRows;i++) { |
| 10 | +pacificQueue.add(newint[]{i,0}); |
| 11 | +atlanticQueue.add(newint[]{i,numCols -1}); |
| 12 | + } |
| 13 | +for (inti =0;i <numCols;i++) { |
| 14 | +pacificQueue.add(newint[]{0,i}); |
| 15 | +atlanticQueue.add(newint[]{numRows -1,i}); |
| 16 | + } |
| 17 | +boolean[][]pacificReachable =bfs(pacificQueue,heights); |
| 18 | +boolean[][]atlanticReachable =bfs(atlanticQueue,heights); |
| 19 | +List<List<Integer>>result =newArrayList<>(); |
| 20 | +for (inti =0;i <numRows;i++) { |
| 21 | +for (intj =0;j <numCols;j++) { |
| 22 | +if (pacificReachable[i][j] &&atlanticReachable[i][j]) { |
| 23 | +result.add(Arrays.asList(i,j)); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | +returnresult; |
| 28 | + } |
| 29 | + |
| 30 | +privateboolean[][]bfs(Queue<int[]>queue,int[][]heights) { |
| 31 | +intnumRows =heights.length; |
| 32 | +intnumCols =heights[0].length; |
| 33 | +boolean[][]reachable =newboolean[numRows][numCols]; |
| 34 | +while (!queue.isEmpty()) { |
| 35 | +int[]removed =queue.remove(); |
| 36 | +intx =removed[0]; |
| 37 | +inty =removed[1]; |
| 38 | +reachable[x][y] =true; |
| 39 | +for (int[]dir :DIRS) { |
| 40 | +intnewX =x +dir[0]; |
| 41 | +intnewY =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(newint[]{newX,newY}); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | +returnreachable; |
| 51 | + } |
| 52 | +} |