classSolution{publicList<List<Integer>>pacificAtlantic(int[][] heights){List<List<Integer>> res =newArrayList<>();finalintROWS= heights.length,COLS= heights[0].length;boolean[][] pacific =newboolean[ROWS][COLS];boolean[][] atlantic =newboolean[ROWS][COLS];for(int c =0; c <COLS;++c){// Go through the first rowdfs(heights,0, c,Integer.MIN_VALUE, pacific);// Last rowdfs(heights,ROWS-1, c,Integer.MIN_VALUE, atlantic);}for(int r =0; r <ROWS;++r){// Go through first columndfs(heights, r,0,Integer.MIN_VALUE, pacific);// Last columndfs(heights, r,COLS-1,Integer.MIN_VALUE, atlantic);}// Save the cell that can reach pacific and atlanticfor(int r =0; r <ROWS;++r){for(int c =0; c <COLS;++c){if(pacific[r][c]&& atlantic[r][c]){
res.add(List.of(r, c));}}}return res;}privatevoiddfs(int[][] heights,int row,int col,int prev,boolean[][] ocean
){// Check in boundif(row <0|| row >= ocean.length || col <0|| col >= ocean[0].length)return;// Check reachable -> pacific | 1 | 2 | 3// Previous must be smaller or equal to the currentif(heights[row][col]< prev || ocean[row][col])return;// Current cell can reach one of the ocean
ocean[row][col]=true;// Check North, South, East, and Westdfs(heights, row +1, col, heights[row][col], ocean);dfs(heights, row -1, col, heights[row][col], ocean);dfs(heights, row, col +1, heights[row][col], ocean);dfs(heights, row, col -1, heights[row][col], ocean);}}