Given anm 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).
tag: BFS
class Solution {
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> ans = new ArrayList<>();
if (matrix == null || matrix.length == 0) return ans;
int n = matrix.length, m = matrix[0].length;
boolean[][] pVisited = new boolean[n][m];
boolean[][] aVisited = new boolean[n][m];
Queue<int[]> pQueue = new LinkedList<>();
Queue<int[]> aQueue = new LinkedList<>();
// row
for (int i = 0; i < n; i++){
pVisited[i][0] = true;
aVisited[i][m - 1] = true;
pQueue.add(new int[]{i, 0, matrix[i][0]});
aQueue.add(new int[]{i, m - 1, matrix[i][m - 1]});
}
// col
for (int j = 0; j < m; j++){
pVisited[0][j] = true;
aVisited[n - 1][j] = true;
pQueue.add(new int[]{0, j, matrix[0][j]});
aQueue.add(new int[]{n - 1, j, matrix[n - 1][j]});
}
bfs(matrix, pVisited, pQueue);
bfs(matrix, aVisited, aQueue);
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (pVisited[i][j] && aVisited[i][j]) ans.add(new int[]{i, j});
}
}
return ans;
}
private void bfs(int[][] matrix, boolean[][] visited, Queue<int[]> q){
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!q.isEmpty()){
int[] cur = q.poll();
for (int i = 0; i < 4; i++){
int xx = cur[0] + dirs[i][0];
int yy = cur[1] + dirs[i][1];
if (xx < 0 || xx >= matrix.length || yy < 0 || yy >= matrix[0].length || visited[xx][yy] || cur[2] > matrix[xx][yy]) continue;
visited[xx][yy] = true;
q.offer(new int[]{xx, yy, matrix[xx][yy]});
}
}
}
}