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).

Solution

public class Solution {
    public List<int[]> pacificAtlantic(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return new ArrayList<int[]>();

        int m = matrix.length;
        int n = matrix[0].length;

        int pacific[][] = new int[m][n];
        int atlantic[][] = new int[m][n];

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i == 0 || j == 0) {
                    if(pacific[i][j] == 0) {
                        dfs(i, j, pacific, matrix);
                    }
                }

                if(i == m-1 || j == n-1) {
                    if(atlantic[i][j] == 0) {
                        dfs(i, j, atlantic, matrix);
                    }
                }
            }
        }


        List<int[]> ans = new ArrayList<int[]>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(atlantic[i][j] == 1 && pacific[i][j] == 1) {
                    ans.add(new int[]{i,j});
                }
            }
        }
        return ans;
    }

    public void dfs(int i, int j, int[][] pacific, int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        if(i < 0 || i >= m || j < 0 || j >= n) return;
        if(pacific[i][j] == 1) return;
        pacific[i][j] = 1;

        if(i < m - 1 && matrix[i][j] <= matrix[i+1][j]) dfs(i+1, j, pacific, matrix);
        if(i > 0 && matrix[i][j] <= matrix[i-1][j]) dfs(i-1, j, pacific, matrix);

        if(j < n - 1 && matrix[i][j] <= matrix[i][j+1]) dfs(i, j+1, pacific, matrix);
        if(j > 0 && matrix[i][j] <= matrix[i][j-1]) dfs(i, j-1, pacific, matrix);
    }
}

results matching ""

    No results matching ""