417. Pacific Atlantic Water Flow

Description

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.

Constraints

Approach

  • GeeksforGeeks

  • ProgramCreek

  • YouTube

Examples

Input: [[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]]

Output: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]

Explanation:

Solutions

/**
 * Time complexity : O(N^2)
 * Space complexity : O(N^2)
 */

class Solution {
    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        List<List<Integer>> result = new ArrayList();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }
        
        int m = matrix.length, n = matrix[0].length;
        boolean[][] pacific = new boolean[m][n];
        boolean[][] atlantic = new boolean[m][n];
        
        for(int j = 0; j < n; j++) {
            dfs(0, j, pacific, matrix, Integer.MIN_VALUE);
            dfs(m-1, j, atlantic, matrix, Integer.MIN_VALUE);
        }
        
        for(int i = 0; i < m; i++) {
            dfs(i, 0, pacific, matrix, Integer.MIN_VALUE);
            dfs(i, n-1, atlantic, matrix, Integer.MIN_VALUE);
        }
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(pacific[i][j] && atlantic[i][j]) {
                    result.add(Arrays.asList(i, j));
                }
            }
        }
        
        return result;
    }
    
    private void dfs(int i, 
                    int j, 
                    boolean[][] canReach, 
                    int[][] matrix, 
                    int prevHeight) {
        if(i < 0 || i >= matrix.length || 
            j < 0 || j >= matrix[0].length || 
            canReach[i][j] || 
            matrix[i][j] < prevHeight) {
            return;
        }
        
        canReach[i][j] = true;
        
        dfs(i+1, j, canReach, matrix, matrix[i][j]);
        dfs(i-1, j, canReach, matrix, matrix[i][j]);
        dfs(i, j-1, canReach, matrix, matrix[i][j]);
        dfs(i, j+1, canReach, matrix, matrix[i][j]);
    }
}

Follow up

Last updated

Was this helpful?