LeetCode417-太平洋大西洋水流问题

题目链接

英文链接:https://leetcode.com/problems/pacific-atlantic-water-flow/

中文链接:https://leetcode-cn.com/problems/pacific-atlantic-water-flow/

题目详述

给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。

规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。

请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。

提示:

  1. 输出坐标的顺序不重要
  2. mn 都小于150

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
给定下面的 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]] (上图中带括号的单元).

题目详解

DFS。找到既能流动到太平洋,也能流动到大西洋的位置位置。

LeetCode130-被围绕的区域 是类似的原理,将问题转化为找到从太平洋逆流而上与从大西洋逆流而上的交点位置集合。

  • 从太平洋的两个边界和大西洋的两个边界开始进行深搜。
  • 把从太平洋逆流而上的区域全部做标记(fromPacific 置 true)。
  • 把从大西洋逆流而上的区域全部做另一个标记(fromAtlantic 置 true)。
  • 两个标记均有的位置就满足要求,加入结果集合即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class LeetCode_00417 {

public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> res = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return res;
}
int m = matrix.length;
int n = matrix[0].length;
boolean[][] fromPacific = new boolean[m][n];
boolean[][] fromAtlantic = new boolean[m][n];
for (int i = 0; i < m; ++i) {
dfs(matrix, fromPacific, i, 0);
dfs(matrix, fromAtlantic, i, n - 1);
}
for (int i = 0; i < n; ++i) {
dfs(matrix, fromPacific, 0, i);
dfs(matrix, fromAtlantic, m - 1, i);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
// 同时满足
if (fromPacific[i][j] && fromAtlantic[i][j]) {
res.add(new int[] {i, j});
}
}
}
return res;
}

private void dfs(int[][] matrix, boolean[][] fromOcean, int i, int j) {
// 已经可以到达
if (fromOcean[i][j]) {
return;
}
fromOcean[i][j] = true;
if (i - 1 >= 0 && matrix[i - 1][j] >= matrix[i][j]) {
dfs(matrix, fromOcean, i - 1, j);
}
if (i + 1 < matrix.length && matrix[i + 1][j] >= matrix[i][j]) {
dfs(matrix, fromOcean, i + 1, j);
}
if (j - 1 >= 0 && matrix[i][j - 1] >= matrix[i][j]) {
dfs(matrix, fromOcean, i, j - 1);
}
if (j + 1 < matrix[0].length && matrix[i][j + 1] >= matrix[i][j]) {
dfs(matrix, fromOcean, i, j + 1);
}
}
}