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

一刷
题解:
从太平洋和大西洋出发,通过dfs,标记途中的点,表示能到达大西洋/太平洋。

public class Solution {
    int[][] dirs = new int[][]{{0,1}, {1, 0}, {0, -1}, {-1, 0}};
    int n;
    int m;
    
    public List pacificAtlantic(int[][] matrix) {
        List res = new LinkedList<>();
        if(matrix==null || matrix.length ==0 || matrix[0].length == 0) return res;
        n = matrix.length;
        m = matrix[0].length;
        boolean[][] pacific = new boolean[n][m];
        boolean[][] atlantic = new boolean[n][m];
        for(int i=0; i=n || y>=m || visited[x][y] || matrix[x][y]

二刷
思路同上

class Solution {
    int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
    int m, n;
    public List pacificAtlantic(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return new ArrayList<>();
        m = matrix.length;
        n = matrix[0].length;
        List res = new ArrayList<>();
        boolean[][] pacifit = new boolean[m][n];
        boolean[][] atlantic = new boolean[m][n];
        
        for(int i=0; i=m || y<0 || y>=n || matrix[i][j]>matrix[x][y] || visited[x][y]) continue;
            dfs(matrix, visited, x, y);
        }
    }
}

你可能感兴趣的:(417. Pacific Atlantic Water Flow)