Skip to content

Commit b399cbb

Browse files
committed
Add week 9 solutions: pacificAtlanticWaterFlow
1 parent bfb932f commit b399cbb

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Time Complexity: O(rows + cols)
2+
// Space Complexity: O(rows + cols)
3+
4+
var pacificAtlantic = function (heights) {
5+
const rows = heights.length;
6+
const cols = heights[0].length;
7+
8+
// initialize matrices to keep track of cells reachable by Pacific and Atlantic
9+
const pacific = [];
10+
const atlantic = [];
11+
12+
// create 2D arrays filled with false values
13+
for (let i = 0; i < rows; i++) {
14+
pacific.push(new Array(cols).fill(false));
15+
atlantic.push(new Array(cols).fill(false));
16+
}
17+
18+
// directions for moving up, right, down, left
19+
const directions = [
20+
[0, 1],
21+
[1, 0],
22+
[0, -1],
23+
[-1, 0],
24+
];
25+
26+
// helper to do DFS
27+
function dfs(row, col, ocean) {
28+
// mark the cell as reachable
29+
ocean[row][col] = true;
30+
for (const [dx, dy] of directions) {
31+
// check all 4 directions
32+
const newRow = row + dx;
33+
const newCol = col + dy;
34+
// continue if the new cell is within bounds, not visited, and has a height greater than or equal to the current cell
35+
if (
36+
newRow >= 0 &&
37+
newRow < rows &&
38+
newCol >= 0 &&
39+
newCol < cols &&
40+
!ocean[newRow][newCol] &&
41+
heights[newRow][newCol] >= heights[row][col]
42+
) {
43+
dfs(newRow, newCol, ocean);
44+
}
45+
}
46+
}
47+
48+
// start DFS from the Pacific ocean borders
49+
for (let i = 0; i < rows; i++) {
50+
// left edge
51+
dfs(i, 0, pacific);
52+
// right edge
53+
dfs(i, cols - 1, atlantic);
54+
}
55+
56+
// start DFS from the Atlantic ocean borders
57+
for (let j = 0; j < cols; j++) {
58+
// top edge
59+
dfs(0, j, pacific);
60+
dfs(rows - 1, j, atlantic); // Bottom edge
61+
}
62+
63+
const result = [];
64+
// check each cell can reach both oceans
65+
for (let i = 0; i < rows; i++) {
66+
for (let j = 0; j < cols; j++) {
67+
if (pacific[i][j] && atlantic[i][j]) {
68+
// if it can reach both
69+
result.push([i, j]);
70+
}
71+
}
72+
}
73+
74+
// return the final list
75+
return result;
76+
};

0 commit comments

Comments
 (0)