Skip to content

Commit 10075ba

Browse files
committed
https://leetcode.cn/problems/shortest-path-visiting-all-nodes
1 parent 264e470 commit 10075ba

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Step 2. Add the dependency
4545

4646
<summary>展开查看</summary>
4747

48+
https://leetcode.cn/problems/shortest-path-visiting-all-nodes
49+
4850
https://leetcode.cn/problems/shortest-path-to-get-all-keys
4951

5052
https://leetcode.cn/problems/removing-minimum-and-maximum-from-array

shortest-path-to-get-all-keys/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,9 @@ export default function shortestPathAllKeys(g: string[]): number {
4040
"A" <= c &&
4141
c <= "Z" &&
4242
((cur >> (c.charCodeAt(0) - "A".charCodeAt(0))) & 1) == 0
43-
)
43+
) {
4444
continue;
45+
}
4546
let ncur = cur;
4647
if ("a" <= c && c <= "z") {
4748
ncur |= 1 << (c.charCodeAt(0) - "a".charCodeAt(0));
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function shortestPathLength(graph: number[][]) {
2+
const n = graph.length;
3+
const queue: number[][] = [];
4+
const seen: boolean[][] = new Array(n)
5+
.fill(0)
6+
.map(() => new Array(1 << n).fill(false));
7+
for (let i = 0; i < n; ++i) {
8+
queue.push([i, 1 << i, 0]);
9+
seen[i][1 << i] = true;
10+
}
11+
12+
let ans = 0;
13+
while (queue.length) {
14+
const tuple = queue.shift() as [number, number, number];
15+
const u = tuple[0],
16+
mask = tuple[1],
17+
dist = tuple[2];
18+
if (mask === (1 << n) - 1) {
19+
ans = dist;
20+
break;
21+
}
22+
// 搜索相邻的节点
23+
for (const v of graph[u]) {
24+
// 将 mask 的第 v 位置为 1
25+
const maskV = mask | (1 << v);
26+
if (!seen[v][maskV]) {
27+
queue.push([v, maskV, dist + 1]);
28+
seen[v][maskV] = true;
29+
}
30+
}
31+
}
32+
return ans;
33+
}
34+
export default shortestPathLength;

0 commit comments

Comments
 (0)