Algorithm


Problem Name: 417. Pacific Atlantic Water Flow

There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.

The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).

The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.

Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

 

Example 1:

Input: heights = [[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]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below:
[0,4]: [0,4] -> Pacific Ocean 
       [0,4] -> Atlantic Ocean
[1,3]: [1,3] -> [0,3] -> Pacific Ocean 
       [1,3] -> [1,4] -> Atlantic Ocean
[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean 
       [1,4] -> Atlantic Ocean
[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean 
       [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean
[3,0]: [3,0] -> Pacific Ocean 
       [3,0] -> [4,0] -> Atlantic Ocean
[3,1]: [3,1] -> [3,0] -> Pacific Ocean 
       [3,1] -> [4,1] -> Atlantic Ocean
[4,0]: [4,0] -> Pacific Ocean 
       [4,0] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.

Example 2:

Input: heights = [[1]]
Output: [[0,0]]
Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.

 

Constraints:

  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 105

Code Examples

#1 Code Example with C Programming

Code - C Programming


int dfs(int *visited, int **matrix, int rowsz, int colsz, int x, int y, int ocean) {
    int a, b, c, d, o;
    int k;
    
    if ((ocean == 0 && (x == 0 || y == 0)) ||
        (ocean == 1 && (x == rowsz - 1 || y == colsz - 1))) {
        return 1;
    }
    
    visited[x * colsz + y] = 1;
    
    o = matrix[x][y];
    a = (x > 0 && visited[(x - 1) * colsz + y] == 0) ? matrix[x - 1][y] : o + 1;
    b = (x  <  rowsz - 1 && visited[(x + 1) * colsz + y] == 0) ? matrix[x + 1][y] : o + 1;
    c = (y > 0 && visited[x * colsz + (y - 1)] == 0) ? matrix[x][y - 1] : o + 1;
    d = (y  <  colsz - 1 && visited[x * colsz + (y + 1)] == 0) ? matrix[x][y + 1] : o + 1;
    
    k = 0;
    if (k == 0 && o >= a) {
        k = dfs(visited, matrix, rowsz, colsz, x - 1, y, ocean);
    }
    if (k == 0 && o >= b) {
        k = dfs(visited, matrix, rowsz, colsz, x + 1, y, ocean);
    }
    if (k == 0 && o >= c) {
        k = dfs(visited, matrix, rowsz, colsz, x, y - 1, ocean);
    }
    if (k == 0 && o >= d) {
        k = dfs(visited, matrix, rowsz, colsz, x, y + 1, ocean);
    }
    
    visited[x * colsz + y] = 0;
    
    return k;
}
int** pacificAtlantic(int** matrix, int matrixRowSize, int matrixColSize, int** columnSizes, int* returnSize) {
    int *visited;
    int *buff;
    int **p;
    int i, j, n;
    
    *returnSize = 0;
    if (matrixRowSize == 0) return NULL;
    
    visited = calloc(matrixRowSize * matrixColSize, sizeof(int));
    buff = malloc(matrixRowSize * matrixColSize * 2 * sizeof(int));
    //assert(buff && visited);
    
    n = 0;
    for (i = 0; i  <  matrixRowSize; i ++) {
        for (j = 0; j  <  matrixColSize; j ++) {
            if (dfs(visited, matrix, matrixRowSize, matrixColSize, i, j, 0) &&
                dfs(visited, matrix, matrixRowSize, matrixColSize, i, j, 1)) {
                buff[n * 2 + 0] = i;
                buff[n * 2 + 1] = j;
                n ++;
            }
        }
    }
​
    free(visited);
    
    *columnSizes = malloc(n * sizeof(int));
    p = malloc(n * sizeof(int *));
    //assert(colbuff && p && *columnSizes);
    for (i = 0; i  <  n; i ++) {
        // every column is size 2, there is really no such a need to return this!!!
        (*columnSizes)[i] = 2;
        p[i] = &buff[i * 2];
    }
​
    *returnSize = n;
    
    return p;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
heights = [[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]]

Output

x
+
cmd
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    vector<pair<int, int>> pacificAtlantic(vector < vector<int>>& matrix) {
        vector < pair<int, int>>res;
        if(matrix.empty()) return res;
        int m = matrix.size(), n = matrix[0].size();
        dir = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
        for(int i = 0; i < m; i++)
            for(int j = 0; j  <  n; j++){
                bool reachP = false, reachA = false;
                DFS(res, matrix, i, j, m, n, reachP, reachA);
                if(reachP && reachA) res.push_back({i, j});
            }
        return res;
    }
    
    void DFS(vector < pair<int, int>>& res, vector < vector<int>>& matrix, int r, int c, int m, int n, bool& reachP, bool& reachA){
        if(matrix[r][c] == -1 || reachP && reachA) return;
        int tmp = matrix[r][c];
        matrix[r][c] = -1;
        for(int i = 0; i  <  4; i++){
            int R = r + dir[i].first, C = c + dir[i].second;
            if(R  <  0 || C < 0) reachP = true;
            else if(R == m || C == n) reachA = true;
            else if(matrix[R][C]  < = tmp) DFS(res, matrix, R, C, m, n, reachP, reachA>;
        }
        matrix[r][c] = tmp;
    }
    
private:
    vector < pair<int, int>>dir;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
heights = [[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]]

Output

x
+
cmd
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
  
  public List < List pacificQueue = new LinkedList<>();
    Queue<int[]> atlanticQueue = new LinkedList<>();
    for (int i = 0; i  <  numRows; i++) {
      pacificQueue.add(new int[]{i, 0});
      atlanticQueue.add(new int[]{i, numCols - 1});
    }
    for (int i = 0; i  <  numCols; i++) {
      pacificQueue.add(new int[]{0, i});
      atlanticQueue.add(new int[]{numRows - 1, i});
    }
    boolean[][] pacificReachable = bfs(pacificQueue, heights);
    boolean[][] atlanticReachable = bfs(atlanticQueue, heights);
    List < List();
    for (int i = 0; i  <  numRows; i++) {
      for (int j = 0; j  <  numCols; j++) {
        if (pacificReachable[i][j] && atlanticReachable[i][j]) {
          result.add(Arrays.asList(i, j));
        }
      }
    }
    return result;
  }
  
  private boolean[][] bfs(Queue < int[]> queue, int[][] heights) {
    int numRows = heights.length;
    int numCols = heights[0].length;
    boolean[][] reachable = new boolean[numRows][numCols];
    while (!queue.isEmpty()) {
      int[] removed = queue.remove();
      int x = removed[0];
      int y = removed[1];
      reachable[x][y] = true;
      for (int[] dir : DIRS) {
        int newX = x + dir[0];
        int newY = y + dir[1];
        if (newX  <  0 || newY < 0 || newX >= numRows || newY >= numCols || reachable[newX][newY]) {
          continue;
        }
        if (heights[newX][newY] >= heights[x][y]) {
          queue.add(new int[]{newX, newY});
        }
      }
    }
    return reachable;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
heights = [[1]]

Output

x
+
cmd
[[0,0]]

#4 Code Example with Javascript Programming

Code - Javascript Programming


const pacificAtlantic = function(matrix) {
  const res = []
  if (!matrix || matrix.length === 0 || matrix[0].length === 0) return res
  const rows = matrix.length
  const cols = matrix[0].length
  const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
  const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false))
  const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false))
  for (let y = 0; y  <  rows; y++) {
    helper(0, y, pacific, -1, matrix, cols, rows, dirs)
    helper(cols - 1, y, atlantic, -1, matrix, cols, rows, dirs)
  }
  for (let x = 0; x  <  cols; x++) {
    helper(x, 0, pacific, -1, matrix, cols, rows, dirs)
    helper(x, rows - 1, atlantic, -1, matrix, cols, rows, dirs)
  }

  for (let y = 0; y  <  rows; y++) {
    for (let x = 0; x  <  cols; x++) {
      if (pacific[y][x] && atlantic[y][x]) {
        res.push([y, x])
      }
    }
  }
  return res
}

function helper(x, y, visited, height, matrix, cols, rows, dirs) {
  if (x < 0 || x >= cols || y < 0 || y >= rows || visited[y][x] || matrix[y][x] < height) return
  visited[y][x] = true
  for (let dir of dirs)
    helper(x + dir[0], y + dir[1], visited, matrix[y][x], matrix, cols, rows, dirs)
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
heights = [[1]]

Output

x
+
cmd
[[0,0]]

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def pacificAtlantic(self, matrix):
        pac, atl, m, n = set(), set(), len(matrix), len(matrix and matrix[0])
        def explore(i, j, ocean): 
            ocean.add((i, j))
            if i > 0 and (i - 1, j) not in ocean and matrix[i - 1][j] >= matrix[i][j]: explore(i - 1, j, ocean)
            if j > 0 and (i, j - 1) not in ocean and matrix[i][j - 1] >= matrix[i][j]: explore(i, j - 1, ocean)
            if i + 1 < m  and (i + 1, j) not in ocean and matrix[i + 1][j] >= matrix[i][j]: explore(i + 1, j, ocean)
            if j + 1 < n  and (i, j +1) not in ocean and matrix[i][j + 1] >= matrix[i][j]: explore(i, j + 1, ocean)
        for i in range(max(m, n)):
            if i < m and (i, 0) not in pac: explore(i, 0, pac)
            if i < n and (0, i) not in pac: explore(0, i, pac)
            if i < n and (m - 1, i) not in atl: explore(m - 1, i, atl)
            if i < m and (i, n - 1) not in atl: explore(i, n - 1, atl)
        return [[x, y] for x, y in pac & atl]
Copy The Code & Try With Live Editor

Input

x
+
cmd
heights = [[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]]

Output

x
+
cmd
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Advertisements

Demonstration


Previous
#416 Leetcode Partition Equal Subset Sum Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#419 Leetcode Battleships in a Board Solution in C, C++, Java, JavaScript, Python, C# Leetcode