Skip to content

Commit 874c915

Browse files
committed
feat: add question 1293
1 parent 0cf059d commit 874c915

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

1293.网格中的最短路径.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* @lc app=leetcode.cn id=1293 lang=javascript
3+
*
4+
* [1293] 网格中的最短路径
5+
*
6+
* 1. 向 4 个方向做 DFS 遍历
7+
* 2. 记录走到当前点时的 k 值, 如果当前点有 k 值且当前 k值 <= 记录的k值, 则说明之前走过该点且优于当前这次结果
8+
* 3. 遍历时碰到障碍就 k - 1
9+
*/
10+
11+
// @lc code=start
12+
/**
13+
* @param {number[][]} grid
14+
* @param {number} k
15+
* @return {number}
16+
*/
17+
var shortestPath = function(grid, k) {
18+
const map = {};
19+
const queue = [{ x: 0, y: 0, k, step: 0 }]
20+
while (queue.length) {
21+
const { x, y, k, step } = queue.shift();
22+
23+
if (map[x * 100 + y] !== undefined && k <= map[x * 100 + y] || k < 0) {
24+
continue;
25+
}
26+
map[x * 100 + y] = k;
27+
28+
if (x === grid.length - 1 && y === grid[0].length - 1) {
29+
return step;
30+
}
31+
32+
if (y + 1 < grid[0].length) {
33+
queue.push({ x, y: y + 1, k: (grid[x][y + 1] === 1 ? k - 1: k), step: step + 1 });
34+
}
35+
if (y - 1 >= 0) {
36+
queue.push({ x, y: y - 1, k: (grid[x][y - 1] === 1 ? k - 1: k), step: step + 1 });
37+
}
38+
if (x + 1 < grid.length) {
39+
queue.push({ x: x + 1, y, k: (grid[x + 1][y] === 1 ? k - 1: k), step: step + 1 })
40+
}
41+
if (x - 1 >= 0) {
42+
queue.push({ x: x - 1, y, k: (grid[x - 1][y] === 1 ? k - 1: k), step: step + 1 })
43+
}
44+
}
45+
46+
return -1;
47+
};
48+
// @lc code=end

0 commit comments

Comments
 (0)