Leetcode 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. Each cell will have water flowing to both its four adjacent cells (north, south, east, west) and/or directly into an ocean. Water can only flow in one direction: from a cell to another one with height equal or lower.
The task is to return the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
[[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]]
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 10^5
pacific
and atlantic
of the same size as the input matrix to keep track of cells that can flow to the respective oceans.pacific
and atlantic
), add it to the result list.Here is the Java code to solve the problem:
import java.util.ArrayList;
import java.util.List;
public class PacificAtlanticWaterFlow {
private int[][] directions = // use example from above
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int m = matrix.length;
int n = matrix[0].length;
boolean[][] pacific = new boolean[m][n];
boolean[][] atlantic = new boolean[m][n];
for (int i = 0; i < m; i++) {
dfs(matrix, pacific, i, 0, Integer.MIN_VALUE);
dfs(matrix, atlantic, i, n - 1, Integer.MIN_VALUE);
}
for (int j = 0; j < n; j++) {
dfs(matrix, pacific, 0, j, Integer.MIN_VALUE);
dfs(matrix, atlantic, m - 1, j, Integer.MIN_VALUE);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j]) {
result.add(new int[]{i, j});
}
}
}
return result;
}
private void dfs(int[][] matrix, boolean[][] visited, int i, int j, int prevHeight) {
int m = matrix.length;
int n = matrix[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || matrix[i][j] < prevHeight) {
return;
}
visited[i][j] = true;
for (int[] dir : directions) {
dfs(matrix, visited, i + dir[0], j + dir[1], matrix[i][j]);
}
}
}
pacific
and atlantic
.This efficient solution ensures we cover all possible flows in the matrix while maintaining only necessary data.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?