[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.
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).
Solution
class Solution {
public List pacificAtlantic(int[][] matrix) {
List 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);
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.