Java implementation LeetCode 417 Pacific Atlantic water problem

417. Pacific Atlantic water problem

Given a non-negative integer mxn matrix represents the height of an individual cell on the mainland. "Pacific" in the left and on the border of the continent, and "Atlantic" in the right border of the continent and the lower boundary.

Only in accordance with a predetermined flow up, down, left, and right direction of the flow, or from high to low and can only flow in the same height.

Please identify those water can flow both to "Pacific", but also to coordinate the flow of "Atlantic" land unit.

prompt:

The order does not matter output coordinates
m and n are less than 150

Example:

Given the following 5x5 matrix:

  太平洋 ~   ~   ~   ~   ~ 
       ~  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  *
          *   *   *   *   * 大西洋

return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (the above figure in parentheses unit).

class Solution {
         private int row, col;
    private int[][] grid;
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        row = matrix.length;
        if (row == 0) {
            return result;
        }
        col = matrix[0].length;
        grid = new int[row][col];
        for (int i = 0; i < row; i++) {
            helper(matrix, i, 0, 1);
        }
        for (int j = 0; j < col; j++) {
            helper(matrix, 0, j, 1);
        }
        for (int i = 0; i < row; i++) {
            helper(matrix, i, col - 1, 2);
        }
        for (int j = 0; j < col; j++) {
            helper(matrix, row - 1, j, 2);
        }
        return result;
    }

    private void helper(int[][] matrix, int i, int j, int v) {
        if (grid[i][j] == v || grid[i][j] == 3) {
            return;
        }
        grid[i][j] += v;
        if (grid[i][j] == 3) {
            List<Integer> temp = new ArrayList<>();
            temp.add(i);
            temp.add(j);
            result.add(temp);
        }
        if (i != 0 && matrix[i - 1][j] >= matrix[i][j]) {
            helper(matrix, i - 1, j, v);
        }
        if (j != 0 && matrix[i][j - 1] >= matrix[i][j]) {
            helper(matrix, i, j - 1, v);
        }
        if (i != row - 1 && matrix[i + 1][j] >= matrix[i][j]) {
            helper(matrix, i + 1, j, v);
        }
        if (j != col - 1 && matrix[i][j + 1] >= matrix[i][j]) {
            helper(matrix, i, j + 1, v);
        }
    }
 
}
Released 1532 original articles · won praise 20000 + · views 2.08 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104878984