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:
- The order of returned grid coordinates does not matter.
- Both m and n are less than 150.
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).
I thought at first that we can use DP, from the boarders search till the other end. It turns out that DP will miss some of the cases. Here we should use DFS. Using two different boolean matrix for pacific and atlantic, then starting from boarders and visiting all possible flows (low -> high because we start from boarder). In the end if the point is true for both matrices, we add it to result.
public class Solution {
private static final int dx[] = {0, 0, -1, 1};
private static final int dy[] = {1, -1, 0, 0};
public List pacificAtlantic(int[][] matrix) {
List rst = new ArrayList();
if (matrix.length == 0 || matrix[0].length == 0) {
return rst;
}
int rows = matrix.length;
int cols = matrix[0].length;
boolean pacific[][] = new boolean[rows][cols];
boolean atlantic[][] = new boolean[rows][cols];
for(int i = 0; i < rows ;i++){
flow(pacific, matrix, i, 0);
flow(atlantic, matrix,i, cols - 1);
}
for(int j = 0; j < cols; j++){
flow(pacific, matrix, 0, j);
flow(atlantic,matrix, rows - 1, j);
}
for(int i = 0;i < rows; i++){
for(int j = 0; j < cols; j++){
if(pacific[i][j] && atlantic[i][j])
rst.add(new int[] {i, j});
}
}
return rst;
}
private void flow(boolean visited[][],int matrix[][],int x,int y){
visited[x][y] = true;
for(int i = 0;i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < matrix.length && ny >= 0 && ny < matrix[0].length
&& !visited[nx][ny] && matrix[nx][ny] >= matrix[x][y]){
flow(visited, matrix, nx, ny);
}
}
}
}