LeetCode 417. Pacific Atlantic Water Flow

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:

  1. The order of returned grid coordinates does not matter.
  2. 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> 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> res = new ArrayList<>();
        for(int i = 0;i=0 && new_row=0 && new_col=matrix[row][col] && !marked[new_row][new_col] ){
                dfs(new_row, new_col, matrix, marked);
            }
        }
        
    }
    

    
}

 

你可能感兴趣的:(LeetCode 417. Pacific Atlantic Water Flow)