Skip to content

Commit 6ced330

Browse files
committed
Add week 9 solutions: pacific-atlantic-water-flow
1 parent 1fc5dcf commit 6ced330

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* https://leetcode.com/problems/two-sum
3+
* time complexity : O(m x m)
4+
* space complexity : O(m x n)
5+
*/
6+
function pacificAtlantic(heights: number[][]): number[][] {
7+
const m = heights.length;
8+
const n = heights[0].length;
9+
const pacific: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false));
10+
const atlantic: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false));
11+
12+
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
13+
14+
function dfs(r: number, c: number, visited: boolean[][], prevHeight: number) {
15+
if (r < 0 || c < 0 || r >= m || c >= n || visited[r][c] || heights[r][c] < prevHeight) {
16+
return;
17+
}
18+
visited[r][c] = true;
19+
for (const [dr, dc] of directions) {
20+
dfs(r + dr, c + dc, visited, heights[r][c]);
21+
}
22+
}
23+
24+
for (let i = 0; i < m; i++) {
25+
dfs(i, 0, pacific, heights[i][0]);
26+
dfs(i, n - 1, atlantic, heights[i][n - 1]);
27+
}
28+
for (let i = 0; i < n; i++) {
29+
dfs(0, i, pacific, heights[0][i]);
30+
dfs(m - 1, i, atlantic, heights[m - 1][i]);
31+
}
32+
33+
const result: number[][] = [];
34+
35+
for (let r = 0; r < m; r++) {
36+
for (let c = 0; c < n; c++) {
37+
if (pacific[r][c] && atlantic[r][c]) {
38+
result.push([r, c]);
39+
}
40+
}
41+
}
42+
43+
return result;
44+
}

0 commit comments

Comments
 (0)