Skip to content

Commit b94705e

Browse files
committed
Create 1391.检查网格中是否存在有效路径.js
1 parent 16c6792 commit b94705e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
给予队列做 BFS 搜索
3+
每个街道有两个口, 其中一个口会走到你来的方向, 这种情况是非法的, 因此用 Set 记录下走过的点, 排除这种情况
4+
d 用于获取每个格子可以前进的下一个点, key 是当前点的街道类型, value 是街道两个口, 每个口由 [x 坐标增量, y 坐标增量, 下个点可以连起来的街道类型] 三部分组成
5+
遍历当前点的下一个可行点, 可行就加到 queue
6+
*/
7+
8+
/**
9+
* @param {number[][]} grid
10+
* @return {boolean}
11+
*/
12+
var hasValidPath = function(grid) {
13+
const aaa = new Set([1, 4, 6]);
14+
const bbb = new Set([2, 5, 6]);
15+
const d = {
16+
1: [[0, -1, new Set([1, 4, 6])], [0, +1, new Set([1, 3, 5])]],
17+
2: [[-1, 0, new Set([2, 3, 4])], [+1, 0, new Set([2, 5, 6])]],
18+
3: [[0, -1, new Set([1, 4, 6])], [+1, 0, new Set([2, 5, 6])]],
19+
4: [[0, +1, new Set([1, 3, 5])], [+1, 0, new Set([2, 5, 6])]],
20+
5: [[0, -1, new Set([1, 4, 6])], [-1, 0, new Set([2, 3, 4])]],
21+
6: [[0, +1, new Set([1, 3, 5])], [-1, 0, new Set([2, 3, 4])]],
22+
}
23+
const set = new Set();
24+
const key = (a, b) => a + ',' + b;
25+
const isValid = (a, b, s) => grid[a] && grid[a][b] && s.has(grid[a][b]);
26+
const queue = [[0, 0]];
27+
while (queue.length) {
28+
const [x, y] = queue.shift();
29+
if (set.has(key(x, y))) {
30+
continue;
31+
}
32+
33+
set.add(key(x, y));
34+
if (x === grid.length - 1 && y === grid[0].length - 1) {
35+
return true;
36+
}
37+
for (const [dx, dy, s] of d[grid[x][y]]) {
38+
if (isValid(x + dx, y + dy, s) && !set.has(x + dx, y + dy)) {
39+
queue.push([x + dx, y + dy]);
40+
}
41+
}
42+
}
43+
return false;
44+
};

0 commit comments

Comments
 (0)