问题描述
有一个 m × n
的矩形岛屿,与 太平洋 和 大西洋 相邻。 “太平洋” 处于大陆的左边界和上边界,而 “大西洋” 处于大陆的右边界和下边界。
这个岛被分割成一个由若干方形单元格组成的网格。给定一个 m x n
的整数矩阵 heights
, heights[r][c]
表示坐标 (r, c)
上单元格 高于海平面的高度 。
岛上雨水较多,如果相邻单元格的高度 小于或等于 当前单元格的高度,雨水可以直接向北、南、东、西流向相邻单元格。水可以从海洋附近的任何单元格流入海洋。
返回网格坐标 result
的 2D 列表 ,其中 result[i] = [ri, ci]
表示雨水从单元格 (ri, ci)
流动 既可流向太平洋也可流向大西洋 。
示例 1:
输入: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
输出: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
示例 2:
输入: heights = [[2,1],[1,2]]
输出: [[0,0],[0,1],[1,0],[1,1]]
提示:
m == heights.length
n == heights[r].length
1 <= m, n <= 200
0 <= heights[r][c] <= 105
解题思路与代码实现
从太平洋边上的节点 逆流而上,将遍历过的节点都标记上。 从大西洋的边上节点 逆流而长,将遍历过的节点也标记上。 然后两方都标记过的节点就是既可以流太平洋也可以流大西洋的节点。
从太平洋边上节点出发,如图:
从大西洋边上节点出发,如图:
class Solution {
private int[][] directions = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; // 方向数组,记录上下左右移动时的坐标变化
public List<List<Integer>> pacificAtlantic(int[][] heights) {
List<List<Integer>> res = new ArrayList<>();
int rowSize = heights.length, colSize = heights[0].length;
boolean[][] pacific = new boolean[rowSize][colSize]; // pacific标记数组
boolean[][] atlantic = new boolean[rowSize][colSize]; // atlantic标记数组
// 水从左右边界向中间蔓延
for (int row = 0; row < rowSize; row++) {
pacific[row][0] = true; // 第一列
atlantic[row][colSize - 1] = true; // 最后一列
dfs(heights, row, 0, pacific); // dfs
dfs(heights, row, colSize - 1, atlantic);
}
// 水从上下边界向中间蔓延
for (int col = 0; col < colSize; col++) {
pacific[0][col] = true; // 第一行
atlantic[rowSize - 1][col] = true; // 最后一行
dfs(heights, 0, col, pacific); // dfs
dfs(heights, rowSize - 1, col, atlantic);
}
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (pacific[i][j] && atlantic[i][j]) {
res.add(List.of(i, j));
}
}
}
return res;
}
private void dfs(int[][] heights, int x, int y, boolean[][] visited) {
for (int i = 0; i < directions.length; i++) {
// 探寻是否能向四周移动
int[] direction = directions[i];
int nextX = x + direction[0];
int nextY = y + direction[1];
// 判断nextX,nextY是否越界
if (nextX >= heights.length || nextX < 0 || nextY < 0 || nextY >= heights[0].length) {
continue;
}
// 判断水是否可以新的[nextX, nextY]点(判断是否能像更高处流动)或者已访问过
if (heights[x][y] > heights[nextX][nextY] || visited[nextX][nextY]) {
continue;
}
visited[nextX][nextY] = true;
dfs(heights, nextX, nextY, visited); // 递归
}
}
}
踩坑点
直接每个点DFS部分用例超时