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

Solution:

class Solution {
    int[] dx = {-1, 0, 0, 1};
    int[] dy = {0, -1, 1, 0};
    
    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return new ArrayList();
        int m = matrix.length, n = matrix[0].length;

        boolean[][] pac = new boolean[m][n];
        boolean[][] atl = new boolean[m][n];
        
        List<List<Integer>> result = new ArrayList();
        for (int i = 0; i < m; i ++) {
            dfs(matrix, pac, i, 0);
            dfs(matrix, atl, i, n - 1);
        }        
        for (int j = 0; j < n; j ++) {
            dfs(matrix, pac, 0, j);
            dfs(matrix, atl, m - 1, j);
        }
        // for (boolean[] p : pac) System.out.println(Arrays.toString(p));
        // System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        // for (boolean[] a : atl) System.out.println(Arrays.toString(a));
        for (int i = 0; i < m; i ++) {
            for (int j = 0; j < n; j ++) {
                if (pac[i][j] && atl[i][j]) {
                    result.add(Arrays.asList(i, j));
                }
            }
        }
        return result;
    }
    
    private void dfs(int[][] matrix, boolean[][] visited, int i, int j) {
        int m = matrix.length, n = matrix[0].length;   
        visited[i][j] = true; 
        for (int k = 0; k < 4; k ++) {
            int nx = i + dx[k];
            int ny = j + dy[k];
            if (nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[nx][ny] >= matrix[i][j] && !visited[nx][ny]) {
                dfs(matrix, visited, nx, ny);
            }
        }
    }
}