[LeetCode] 417. Pacific Atlantic Water Flow

43次阅读

共计 1489 个字符,预计需要花费 4 分钟才能阅读完成。

Problem
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 5×5 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).
Solution
class Solution {
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
int m = matrix.length, n = matrix[0].length;
boolean[][] pac = new boolean[m][n];
boolean[][] atl = new boolean[m][n];
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
for (int i = 0; i < m; i++) {
dfs(matrix, pac, dirs, i, 0);
dfs(matrix, atl, dirs, i, n-1);
}
for (int j = 0; j < n; j++) {
dfs(matrix, pac, dirs, 0, j);
dfs(matrix, atl, dirs, m-1, j);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pac[i][j] && atl[i][j]) res.add(new int[]{i,j});
}
}
return res;
}
private void dfs(int[][] matrix, boolean[][] visited, int[][] dirs, int i, int j) {
int m = matrix.length, n = matrix[0].length;
visited[i][j] = true;
for (int[] dir: dirs) {
int x = i+dir[0];
int y = j+dir[1];
if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y] || matrix[x][y] < matrix[i][j]) continue;
else dfs(matrix, visited, dirs, x, y);
}
}
}

正文完
 0