Skip to content

Commit a5353e9

Browse files
authored
Update 778-swim-in-rising-water.js
1 parent 102d709 commit a5353e9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

778-swim-in-rising-water.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const swimInWater = function(grid) {
6+
const n = grid.length
7+
const limit = n * n, { floor } = Math
8+
let l = 0, r = limit - 1
9+
10+
while(l < r) {
11+
const mid = l + floor((r - l) / 2)
12+
if(valid(mid)) r = mid
13+
else l = mid + 1
14+
}
15+
16+
return l
17+
18+
19+
function valid(h) {
20+
const visited = Array.from({ length: n }, () => Array(n).fill(0))
21+
if(grid[0][0] > h) return false
22+
return dfs(h, 0, 0, visited)
23+
}
24+
25+
function dfs(h, i, j, visited) {
26+
if(i === n - 1 && j === n - 1) return true
27+
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
28+
visited[i][j] = 1
29+
for(const [dx, dy] of dirs) {
30+
const nx = i + dx, ny = j + dy
31+
if(nx >= 0 && nx < n && ny >= 0 && ny < n && visited[nx][ny] === 0 && grid[nx][ny] <= h) {
32+
if(dfs(h, nx, ny, visited)) return true
33+
}
34+
35+
}
36+
37+
return false
38+
}
39+
};
40+
41+
// another
42+
43+
144
/**
245
* @param {number[][]} grid
346
* @return {number}

0 commit comments

Comments
 (0)