Given an m x n
matrix of non-negative integers representing the height of each unit cell in a continent, the “Pacific ocean” touches the left and top edges of the matrix and the “Atlantic ocean” touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
Example:
Given the following 5x5 matrix: Pacific ~ ~ ~ ~ ~ ~ 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 * * * * * * Atlantic Return: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
标签:Depth-first Search、Breadth-first Search
给定一个m*n的矩阵,矩阵的每一个元素代表一个大陆的一块区域的高度。矩阵的上边界和左边界外是Pacific,下边界和右边界是Atlantic。水向低处走,所以当前区域的高度高于或等于相邻区域时,水可以从当前区域流向相邻区域。本题要求的点是,从该点出发,既可以流到Pacific也可以流到Atlantic,
本题我采用的广搜的思路,深搜也可以解决但是暂时没有敲出来。从矩阵的四个边界开始进行广搜, 寻找当前点附近的四个点是否可以有水流向当前点。
public class Solution {
public static final int[][] DIR = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> res = new ArrayList<>();
if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0) {
return res;
}
int n = matrix.length;
int m = matrix[0].length;
boolean[][] pacific = new boolean[n][m];
boolean[][] atlantic = new boolean[n][m];
Queue<int[]> pQueue = new LinkedList<>();
Queue<int[]> aQueue = new LinkedList<>();
for (int i = 0; i < n; i++) {
pQueue.offer(new int[] { i, 0 });
aQueue.offer(new int[] { i, m - 1 });
pacific[i][0] = true;
atlantic[i][m - 1] = true;
}
for (int i = 0; i < m; i++) {
pQueue.offer(new int[] { 0, i });
aQueue.offer(new int[] { n - 1, i });
pacific[0][i] = true;
atlantic[n - 1][i] = true;
}
bfs(matrix, pQueue, pacific);
bfs(matrix, aQueue, atlantic);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (pacific[i][j] && atlantic[i][j]) {
res.add(new int[] { i, j });
}
}
}
return res;
}
public void bfs(int[][] matrix, Queue<int[]> queue, boolean[][] isVisited) {
int n = matrix.length;
int m = matrix[0].length;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int[] d : DIR) {
int x = cur[0] + d[0];
int y = cur[1] + d[1];
if (x < 0 || x >= n || y < 0 || y >= m || isVisited[x][y] || matrix[x][y] < matrix[cur[0]][cur[1]]) {
continue;
}
isVisited[x][y] = true;
queue.offer(new int[] { x, y });
}
}
}
}