Skip to content

Commit 9e1e31e

Browse files
committed
pacific atlantic water flow solution
1 parent 99bd132 commit 9e1e31e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
function pacificAtlantic(heights: number[][]): number[][] {
2+
const m = heights.length;
3+
const n = heights[0].length;
4+
5+
const directions = [
6+
[0, 1],
7+
[0, -1],
8+
[1, 0],
9+
[-1, 0],
10+
];
11+
12+
const helper = (row: number, col: number): boolean[][] => {
13+
const canReach: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false));
14+
15+
const queue: [number, number][] = [];
16+
17+
for (let i = 0; i < n; i++) {
18+
canReach[row][i] = true;
19+
queue.push([row, i]);
20+
}
21+
for (let i = 0; i < m; i++) {
22+
canReach[i][col] = true;
23+
queue.push([i, col]);
24+
}
25+
26+
while (queue.length > 0) {
27+
const [cx, cy] = queue.shift()!;
28+
29+
for (const [dx, dy] of directions) {
30+
const [nx, ny] = [cx + dx, cy + dy];
31+
32+
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !canReach[nx][ny] && heights[cx][cy] <= heights[nx][ny]) {
33+
canReach[nx][ny] = true;
34+
queue.push([nx, ny]);
35+
}
36+
}
37+
}
38+
39+
return canReach;
40+
};
41+
42+
const canReachPacific: boolean[][] = helper(0, 0);
43+
const canReachAtlantic: boolean[][] = helper(m - 1, n - 1);
44+
45+
const results: number[][] = [];
46+
47+
for (let i = 0; i < m; i++) {
48+
for (let j = 0; j < n; j++) {
49+
if (canReachPacific[i][j] && canReachAtlantic[i][j]) results.push([i, j]);
50+
}
51+
}
52+
53+
return results;
54+
}

0 commit comments

Comments
 (0)