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<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);
            }
        }
        
    }
    

    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值