417. Pacific Atlantic Water Flow

来源:互联网 发布:5g网络手机 编辑:程序博客网 时间:2024/05/02 01:20

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

public class Solution {    public List<int[]> pacificAtlantic(int[][] matrix) {        List<int[]> res = new ArrayList<int[]>();        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;        int m = matrix.length;        int n = matrix[0].length;        int[][] toP = new int[m][n];        int[][] toA = new int[m][n];        for (int i = 0; i < m; i++) {            toA[i][n-1] = 1;            toP[i][0] = 1;            helper(matrix, toA, i, n-1, m, n);            helper(matrix, toP, i, 0, m, n);        }        for (int i = 0; i < n; i++) {            toA[m-1][i] = 1;            toP[0][i] = 1;            helper(matrix, toA, m-1, i, m, n);            helper(matrix, toP, 0, i, m, n);        }        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if(toA[i][j] == 1 && toP[i][j] == 1){                    res.add(new int[]{i, j});                }            }        }        return res;    }    public void helper(int[][] matrix, int[][] mark, int i, int j, int m, int n) {        if (i > 0 && matrix[i-1][j] >= matrix[i][j] && mark[i-1][j] == 0){            mark[i-1][j] = 1;            helper(matrix, mark, i-1, j, m, n);        }        if (i < m-1 && matrix[i+1][j] >= matrix[i][j] && mark[i+1][j] == 0) {            mark[i+1][j] = 1;            helper(matrix, mark, i+1, j, m, n);        }        if (j > 0 && matrix[i][j-1] >= matrix[i][j] && mark[i][j-1] == 0) {            mark[i][j-1] = 1;            helper(matrix, mark, i, j-1, m, n);        }        if (j < n-1 && matrix[i][j+1] >= matrix[i][j] && mark[i][j+1] == 0) {            mark[i][j+1] = 1;            helper(matrix, mark, i, j+1, m, n);        }    }}
0 0
原创粉丝点击