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).
bfs问题
但是我们不应该从每个陆地位置出发去做bfs,那样会超时的。
事实上,我们只需要从四个边反向dfs即可
class Solution {
private int[][] directions = {
{0,1},{0,-1},{1,0},{-1,0}
};
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
if(matrix.length==0) return new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;
boolean[][] pac = new boolean[m][n];
for(int j = 0;j<n;j++){
dfs(0,j,matrix,pac);
}
for(int i = 0;i<m;i++){
dfs(i,0,matrix,pac);
}
boolean[][] atl = new boolean[m][n];
for(int j = 0;j<n;j++){
dfs(m-1,j,matrix,atl);
}
for(int i = 0;i<m;i++){
dfs(i,n-1,matrix,atl);
}
List<List<Integer>> res = new ArrayList<>();
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
if(pac[i][j] && atl[i][j]){
res.add(Arrays.asList(i,j));
}
}
}
return res;
}
private void dfs(int row,int col,int[][] matrix,boolean[][] marked){
int m = matrix.length;
int n = matrix[0].length;
marked[row][col] = true;
for(int[] direction:directions){
int new_row = row+direction[0];
int new_col = col+direction[1];
if(new_row>=0 && new_row<m && new_col>=0 && new_col<n && matrix[new_row][new_col]>=matrix[row][col] && !marked[new_row][new_col] ){
dfs(new_row, new_col, matrix, marked);
}
}
}
}