1. 題目
2. 思路和題解
從題目中可以看出,如果一個格子上有雨水,那么就可以流到周圍比他高度低的單元格,如果單元格和海洋相鄰,那么雨水也會流入海洋。總而言之一句話就是水從高處流向低處。從這里的流向可以聯想到深度優先搜索這個算法。但是這里我們任意選擇單元格去進行搜索的時候,按照正常的思路,后面會不可避免的遍歷到重復的單元格,這樣會大大的增加搜索時間。所以要換個思路,既然雨水從高流向低,并且靠近海洋的會直接流入海洋,那么我們在采用深度優先搜索的時候,下一個就要去找更大的單元格,利用反向搜索的思路去解決問題。
在進行反向搜索的時候,如果一個單元格既可以從太平洋反向到達,又可以從大西洋反向到達,那么這個單元格就是我們需要的單元格。
代碼實現如下:
class Solution {static int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};int[][] heights;int m, n;public List<List<Integer>> pacificAtlantic(int[][] heights) {this.heights = heights;this.m = heights.length;this.n = heights[0].length;boolean[][] pacific = new boolean[m][n];boolean[][] atlantic = new boolean[m][n];for (int i = 0; i < m; i++) {dfs(i, 0, pacific);}for (int j = 1; j < n; j++) {dfs(0, j, pacific);}for (int i = 0; i < m; i++) {dfs(i, n - 1, atlantic);}for (int j = 0; j < n - 1; j++) {dfs(m - 1, j, atlantic);}List<List<Integer>> result = new ArrayList<List<Integer>>();for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (pacific[i][j] && atlantic[i][j]) {List<Integer> cell = new ArrayList<Integer>();cell.add(i);cell.add(j);result.add(cell);}}}return result;}public void dfs(int row, int col, boolean[][] ocean) {if (ocean[row][col]) {return;}ocean[row][col] = true;for (int[] dir : dirs) {int newRow = row + dir[0], newCol = col + dir[1];if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && heights[newRow][newCol] >= heights[row][col]) {dfs(newRow, newCol, ocean);}}}
}