Skip to content

Commit 74b68d5

Browse files
committed
feat: 2258. Escape the Spreading Fire : BFS
1 parent 1330ac6 commit 74b68d5

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const maximumMinutes = function (g) {
6+
const m = g.length; const n = g[0].length
7+
const fs = []
8+
for (let i = 0; i < m; i++) {
9+
for (let j = 0; j < n; j++) {
10+
if (g[i][j] === 1) fs.push([i, j])
11+
}
12+
}
13+
const p = bfs([[0, 0]]); const f = bfs(fs)
14+
if (p[m - 1][n - 1] === 1e10) return -1
15+
if (f[m - 1][n - 1] === 1e10) return 1e9
16+
if (p[m - 1][n - 1] > f[m - 1][n - 1]) return -1
17+
const D = f[m - 1][n - 1] - p[m - 1][n - 1]
18+
if (getDirection(f) === 'both') return D - 1
19+
if (getDirection(f) === getDirection(p)) return D - 1
20+
return D
21+
22+
function getDirection (f) {
23+
if (f[m - 2][n - 1] === f[m - 1][n - 2]) return 'both'
24+
else if (f[m - 2][n - 1] < f[m - 1][n - 2]) return 'up'
25+
return 'left'
26+
}
27+
function bfs (q) {
28+
const d = Array(m).fill(0).map(() => Array(n).fill(1e10))
29+
for (const [x, y] of q) d[x][y] = 0
30+
while (q.length) {
31+
const [x, y] = q.shift()
32+
for (const [dx, dy] of [[0, 1], [0, -1], [-1, 0], [1, 0]]) {
33+
const i = x + dx; const j = y + dy
34+
if (i >= 0 && i < m && j >= 0 && j < n && g[i][j] !== 2) {
35+
if (d[i][j] !== 1e10) continue
36+
d[i][j] = Math.min(d[i][j], d[x][y] + 1)
37+
q.push([i, j])
38+
}
39+
}
40+
}
41+
return d
42+
}
43+
}

leetcode/残酷刷题/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@
199199
- 2045. Second Minimum Time to Reach Destination
200200
- 1263. Minimum Moves to Move a Box to Their Target Location
201201
- Deque, 只有 0 和 1 两个边权
202+
- 2258. Escape the Spreading Fire
202203

203204
#### 拓扑排序
204205

0 commit comments

Comments
 (0)