Skip to content

Commit 03a3932

Browse files
authored
Create 1293-shortest-path-in-a-grid-with-obstacles-elimination.js
1 parent 3a5bb46 commit 03a3932

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const shortestPath = function (grid, k) {
7+
const m = grid.length
8+
const n = m && grid[0].length
9+
if (m === 1 && n === 1) return 0
10+
const queue = [[0, 0, k]]
11+
const dirs = [
12+
[1, 0],
13+
[-1, 0],
14+
[0, 1],
15+
[0, -1],
16+
]
17+
const visited = new Set()
18+
let steps = 0
19+
while (queue.length > 0) {
20+
let size = queue.length
21+
while (size--) {
22+
const [row, col, em] = queue.shift()
23+
if (visited.has(row + "#" + col + "#" + em)) continue
24+
visited.add(row + "#" + col + "#" + em)
25+
for (let dir of dirs) {
26+
const nx = row + dir[0]
27+
const ny = col + dir[1]
28+
if (
29+
nx < 0 ||
30+
nx >= m ||
31+
ny < 0 ||
32+
ny >= n ||
33+
visited.has(nx + "#" + ny + "#" + em)
34+
)
35+
continue
36+
if (nx === m - 1 && ny === n - 1) return steps + 1
37+
if (grid[nx][ny] === 1) {
38+
if (em > 0) queue.push([nx, ny, em - 1])
39+
} else {
40+
queue.push([nx, ny, em])
41+
}
42+
}
43+
}
44+
steps++
45+
}
46+
return -1
47+
}

0 commit comments

Comments
 (0)