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

解题思路

初步想法:创建一个和输入数组相同规模的数组arr,里面存放的元素为:可以到达太平洋的为1,可以到达大西洋的为2,都可以到达的为3,都不可以到达的为4;这样的话,遍历数组arr,遇到元素为3的,就把该坐标加入到结果list中。问题就转换成了arr数组元素怎么填写。根据题目可以得出arr数组最外面一圈的值是确定的。因为arr[i][j] 的值和该坐标上下左右坐标的值都有关。而在遍历的时候只能单方向遍历,只能从左往右,从上往下或者其他。而且要更新很多遍才可以得到最终的结果。所以用DFS递归的方式更好解决,而且更好理解。

AC代码

下面的实现用的是上面的思想,利用了DFS,而不是数组遍历的方式(当然,递归可以转换为循环)。

class Solution {
    public List<int[]> pacificAtlantic(int[][] matrix) {
        List<int[]> res = new LinkedList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return res;
        }
        int 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; i++){  //第一列和最后一列的每个值都会引起最终结果的更新,即每一次DFS都会访问整个二维数组
            dfs(matrix, pacific, Integer.MIN_VALUE, i, 0);
            dfs(matrix, atlantic, Integer.MIN_VALUE, i, m-1);
        }
        for(int i=0; i<m; i++){//第一行和最后一行的每个值都会引起最终结果的更新
            dfs(matrix, pacific, Integer.MIN_VALUE, 0, i);
            dfs(matrix, atlantic, Integer.MIN_VALUE, n-1, i);
        }
        for (int i = 0; i < n; i++) 
            for (int j = 0; j < m; j++) 
                if (pacific[i][j] && atlantic[i][j]) 
                    res.add(new int[] {i, j});
        return res;
    }

    //方向:下,上,右,左
    int[][]dir = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};

    //根据 height 更新 [x][y] 的值
    public void dfs(int[][]matrix, boolean[][]visited, int height, int x, int y){
        int n = matrix.length, m = matrix[0].length;
        if(x<0 || x>=n || y<0 || y>=m || visited[x][y] || matrix[x][y] < height)
            return;
        visited[x][y] = true;
        for(int[]d:dir){
            dfs(matrix, visited, matrix[x][y], x+d[0], y+d[1]);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/tkzc_csk/article/details/82194171