给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
提示:
输出坐标的顺序不重要
m 和 n 都小于150
示例:
给定下面的 5x5 矩阵:
-
太平洋 ~ ~ ~ ~ ~
- 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]] (上图中带括号的单元).
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pacific-atlantic-water-flow
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路就是:dfs从数组内部开始向外流动,看是否能够到达两洋,求一个交集
class Solution {
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
List<List<Integer>> res = new ArrayList<>(); // 返回的结果数组
int m = matrix.length;
if(m==0) return res;
int n = matrix[0].length;
boolean[][] pacific = new boolean[m][n]; // 能流到两洋的记录数组,最后求一下交集
boolean[][] atlantic = new boolean[m][n]; // 就是能流到两洋的结果数组
//判断从左到右 每一行 是否满足要求,也是dfs去判断当前的高度非递减
for (int row = 0; row < m; row++) {
dfs(matrix, row, 0, matrix[row][0], pacific); // 从边界向内部构建
dfs(matrix, row, n-1, matrix[row][n-1], atlantic);
}
// 判断从上到下 列 是否满足要求 就是dfs去判断当前的高度要非递减
for (int col = 0; col < n; col++) {
dfs(matrix, 0, col, matrix[0][col], pacific); // 上面是太平洋 下面是大西洋
dfs(matrix, m - 1, col, matrix[m-1][col], atlantic);
}
for (int i = 0; i < m; i++) { // 两个保存的结果数组去一下交集,那当前坐标就是满足要求的
for (int j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j]) {
List<Integer> temp = new ArrayList();
temp.add(i);
temp.add(j);
res.add(temp);
}
}
}
return res;
}
/**
* @param matrix 原小岛矩阵
* @param row 行
* @param col 列
* @param preHeight 前一个高度
* @param ocean 两洋布尔矩阵
* @return void
* @author dpfan@mail.ustc.edu.cn
* @date 2020/12/2 9:43
*/
private void dfs(int[][] matrix, int row, int col, int preHeight, boolean[][] ocean){
if ( row<0 || // 当前坐标越界 或者 当前高度小于前一个比对的高度,直接返回 不作处理
row>matrix.length-1 ||
col<0 ||
col>matrix[0].length-1 ||
matrix[row][col] < preHeight ||
ocean[row][col] // 表示当前的boolean矩阵是否为f/t t就是已经处理过了 f就是还没有遍历到
) {return;}
// 否则的话 递归处理ocean矩阵 深度优先遍历 就是求解两个boolean矩阵
ocean[row][col] = true;
dfs(matrix, row+1, col, matrix[row][col], ocean);
dfs(matrix, row-1, col, matrix[row][col], ocean);
dfs(matrix,row, col+1, matrix[row][col], ocean);
dfs(matrix, row, col-1, matrix[row][col], ocean);
}
}