Skip to content

Commit c0d7718

Browse files
committed
Add solution #778
1 parent ea2ff4e commit c0d7718

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,7 @@
588588
773|[Sliding Puzzle](./0773-sliding-puzzle.js)|Hard|
589589
775|[Global and Local Inversions](./0775-global-and-local-inversions.js)|Medium|
590590
777|[Swap Adjacent in LR String](./0777-swap-adjacent-in-lr-string.js)|Medium|
591+
778|[Swim in Rising Water](./0778-swim-in-rising-water.js)|Hard|
591592
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
592593
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
593594
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* 778. Swim in Rising Water
3+
* https://leetcode.com/problems/swim-in-rising-water/
4+
* Difficulty: Hard
5+
*
6+
* You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation
7+
* at that point (i, j).
8+
*
9+
* The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from
10+
* a square to another 4-directionally adjacent square if and only if the elevation of both squares
11+
* individually are at most t. You can swim infinite distances in zero time. Of course, you must
12+
* stay within the boundaries of the grid during your swim.
13+
*
14+
* Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start
15+
* at the top left square (0, 0).
16+
*/
17+
18+
/**
19+
* @param {number[][]} grid
20+
* @return {number}
21+
*/
22+
var swimInWater = function(grid) {
23+
const n = grid.length;
24+
let left = grid[0][0];
25+
let right = n * n - 1;
26+
27+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
28+
29+
const canReachDestination = (time) => {
30+
if (grid[0][0] > time) return false;
31+
32+
const visited = Array(n).fill().map(() => Array(n).fill(false));
33+
const queue = [[0, 0]];
34+
visited[0][0] = true;
35+
36+
while (queue.length > 0) {
37+
const [row, col] = queue.shift();
38+
39+
if (row === n - 1 && col === n - 1) {
40+
return true;
41+
}
42+
43+
for (const [dr, dc] of directions) {
44+
const newRow = row + dr;
45+
const newCol = col + dc;
46+
47+
if (
48+
newRow >= 0 && newRow < n && newCol >= 0 && newCol < n
49+
&& !visited[newRow][newCol] && grid[newRow][newCol] <= time
50+
) {
51+
queue.push([newRow, newCol]);
52+
visited[newRow][newCol] = true;
53+
}
54+
}
55+
}
56+
57+
return false;
58+
};
59+
60+
while (left < right) {
61+
const mid = Math.floor((left + right) / 2);
62+
63+
if (canReachDestination(mid)) {
64+
right = mid;
65+
} else {
66+
left = mid + 1;
67+
}
68+
}
69+
70+
return left;
71+
};

0 commit comments

Comments
 (0)