Pacific Atlantic Water Flow 08/08
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.
1.The order of returned grid coordinates does not matter. 2.Both m and n are less than 150.Have you met this question in a real interview? Yes
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).
和找小岛问题基本一样,用了return type来记录找到两个海洋的情况,用的dfs解题,深度搜索上下左右四
个方向
public class Solution {
/**
* @param matrix: the given matrix
* @return: The list of grid coordinates
*/
class Type{
public boolean inPacific;
public boolean inAtlantic;
public Type(boolean inPacific,boolean inAtlantic){
this.inPacific = inPacific;
this.inAtlantic = inAtlantic;
}
}
private static int[] xposition = {0,1,0,-1};
private static int[] yposition = {1,0,-1,0};
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
// write your code here
List<List<Integer>> res = new ArrayList<>();
if(matrix == null || matrix.length == 0){
return res;
}
boolean[][] isVisited = new boolean[matrix.length][matrix[0].length];
boolean[][] both = new boolean[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length ;++i ){
for(int j = 0; j < matrix[0].length;++j){
isVisited[i][j] = true;
Type t = dfs(i,j,matrix,isVisited,both);
isVisited[i][j] = false;
if(t.inPacific && t.inAtlantic){
List<Integer> list = new ArrayList<>();
list.add(i);
list.add(j);
res.add(list);
}
}
}
return res;
}
public Type dfs(int i, int j, int[][] matrix,boolean[][] isVisited,boolean[][] both){
boolean inP = false,inA = false;
if(both[i][j]){
return new Type(true,true);
}
for(int k = 0; k < 4; ++k){
int x = i + xposition[k];
int y = j +yposition[k];
if(isPacific(x,y,matrix)){
inP = true;
continue;
}
if(isAtlantic(x,y,matrix)){
inA = true;
continue;
}
if(isVisited[x][y]){
continue;
}
if(matrix[x][y] <= matrix[i][j]){
isVisited[x][y] = true;
Type t = dfs(x,y,matrix,isVisited,both);
isVisited[x][y] = false;
if(t.inPacific){
inP = true;
}
if(t.inAtlantic){
inA = true;
}
}
}
if(inA&& inP){
both[i][j] = true;
}
return new Type(inP,inA);
}
public boolean isPacific(int i ,int j,int[][] matrix){
return i == -1 || j == -1;
}
public boolean isAtlantic(int i,int j,int[][] matrix){
return i == matrix.length || j == matrix[0].length;
}
}
Last updated