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).
和装水的题目(407. Trapping Rain Water II)很像,从边界开始dfs或者bfs
public class Solution {
int[] xoff={-1,0,1,0};
int[] yoff={0,-1,0,1};
int m,n;
public List<int[]> pacificAtlantic(int[][] matrix)
{
m=matrix.length;
List<int[]> retlist=new ArrayList<>();
if(m<1)
return retlist;
n=matrix[0].length;
boolean[][] Pacific=new boolean[m][n];
boolean[][] Atlantic=new boolean[m][n];
for(int j=0;j<n;j++)
{
dfs(matrix, 0, j, Pacific);
dfs(matrix, m-1, j,Atlantic);
}
for(int i=0;i<m;i++)
{
dfs(matrix, i, 0, Pacific);
dfs(matrix, i, n-1, Atlantic);
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(Pacific[i][j]&&Atlantic[i][j])
retlist.add(new int[]{i,j});
return retlist;
}
public void dfs(int[][] matrix,int x,int y,boolean[][] visited)
{
visited[x][y]=true;
int height=matrix[x][y];
for(int i=0;i<4;i++)
{
int xx=x+xoff[i];
int yy=y+yoff[i];
if(xx>=0&&xx<m&&yy>=0&&yy<n&&!visited[xx][yy])
if(matrix[xx][yy]>=height)
dfs(matrix, xx, yy, visited);
}
}
}