417. Pacific-Atlantic-Water-Flow

difficulty: Medium

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

Method One

class Solution {
    private int[][] directions = new int[][]{{-1, 0},{1,0},{0,-1},{0,1}}; 
    private int rows;
    private int cols; 
    
    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        // 从太平洋和大西洋的边缘的点开始BFS/DFS。然后找他们并列的地方。
        List<List<Integer>> ans = new ArrayList<>();
        this.rows = matrix.length;
        if( rows < 1 ) {
            return ans;
        }
        this.cols = matrix[0].length;
        
        boolean[][] pacific = new boolean[rows][cols];
        boolean[][] atlantic = new boolean[rows][cols];
        
        Queue<int[]> pQueue = new LinkedList<>();
        Queue<int[]> aQueue = new LinkedList<>();
        
        for(int i = 0 ; i < rows ; i++) {
            pQueue.offer(new int[]{i,0});
            aQueue.offer(new int[]{i,cols - 1});
        }
        for(int j = 0 ; j < cols; j++ ) {
            pQueue.offer(new int[]{0,j});
            aQueue.offer(new int[]{rows - 1, j});
        }
        
        bfs(matrix, pacific, pQueue);
        bfs(matrix, atlantic, aQueue);
        for(int i = 0; i < rows; i++ ) {
            for( int j = 0; j < cols; j++ ) {
                if( pacific[i][j] && atlantic[i][j] ) {
                    List<Integer> pair = new ArrayList<Integer>();
                    pair.add(i);
                    pair.add(j);
                    ans.add(pair);
                }
            }
        }
        return ans;
        
    }
    
    public void bfs(int[][] matrix, boolean[][] marked, Queue<int[]> queue) {
        while(!queue.isEmpty()) {
            int size = queue.size();
            while(size > 0) {
                size -= 1;
                int[] cur = queue.poll();
                int row = cur[0];
                int col = cur[1];
                marked[row][col] = true;
                for(int[] direction: this.directions) {
                    int nextRow = row + direction[0];
                    int nextCol = col + direction[1];
                    if(nextRow < 0 || nextCol < 0 || nextRow >= rows || nextCol >= cols 
                       ||  marked[nextRow][nextCol] || matrix[nextRow][nextCol] < matrix[row][col] ) {
                        continue;
                    }
                    queue.offer(new int[]{nextRow, nextCol});
                }
            }
        }
    }
}

2023年写的大差不差吧。

class Solution {
    public List<List<Integer>> pacificAtlantic(int[][] heights) {

        List<List<Integer>> ans = new ArrayList<>();
        boolean[][] pMarked = bfs(heights, true);
        boolean[][] aMarked = bfs(heights, false);
        for (int i = 0; i < heights.length; i++) {
            for (int j = 0; j < heights[0].length; j++) {
                if (pMarked[i][j] && aMarked[i][j]) {
                    List<Integer> pair = new ArrayList<>();
                    pair.add(i);
                    pair.add(j);
                    ans.add(pair);
                }
            }
        }
        return ans;
    }

    private boolean[][] bfs(int[][] heights, boolean isPacific) {
        int M = heights.length;
        int N = heights[0].length;
        Queue<int[]> queue = new ArrayDeque<>();
        boolean[][] marked = new boolean[M][N];
        int[][] directions = new int[][]{{-1, 0},{1,0},{0,-1},{0,1}}; 
        for (int i = 0; i < M; i++) {
            int[] nextPair = isPacific ? new int[]{i, 0} : new int[]{i, N - 1};
            queue.offer(nextPair);
            marked[nextPair[0]][nextPair[1]] = true;
        }
        for (int j = 0; j < N; j++) {
            int[] nextPair = isPacific ? new int[]{0, j} : new int[]{M - 1, j};
            queue.offer(nextPair);
            marked[nextPair[0]][nextPair[1]] = true;
        }
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                size--;
                int[] cur = queue.poll();
                int curRow = cur[0];
                int curCol = cur[1];
                for (int[] direction : directions) {
                    int nextRow = curRow + direction[0];
                    int nextCol = curCol + direction[1];
                    if (nextRow < 0 || nextCol < 0 || nextRow >= M || nextCol >= N) continue;
                    if (marked[nextRow][nextCol]) continue;
                    if (heights[curRow][curCol] > heights[nextRow][nextCol]) continue;
                    marked[nextRow][nextCol] = true;
                    queue.offer(new int[]{nextRow, nextCol});
                }
            }
        }
        return marked;
    }
}

Last updated

Was this helpful?