Skip to content

Commit 99755b2

Browse files
authored
Create 847-shortest-path-visiting-all-nodes.js
1 parent 19627ce commit 99755b2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[][]} graph
3+
* @return {number}
4+
*/
5+
const shortestPathLength = function(graph) {
6+
const N = graph.length
7+
const dist = Array.from({ length: 1 << N }, () => new Array(N).fill(N * N))
8+
for (let x = 0; x < N; x++) dist[1 << x][x] = 0
9+
for (let cover = 0; cover < 1 << N; cover++) {
10+
let repeat = true
11+
while (repeat) {
12+
repeat = false
13+
for (let head = 0; head < N; head++) {
14+
let d = dist[cover][head]
15+
for (let next of graph[head]) {
16+
let cover2 = cover | (1 << next)
17+
if (d + 1 < dist[cover2][next]) {
18+
dist[cover2][next] = d + 1
19+
if (cover == cover2) repeat = true
20+
}
21+
}
22+
}
23+
}
24+
}
25+
let ans = N * N
26+
for (let cand of dist[(1 << N) - 1]) ans = Math.min(cand, ans)
27+
return ans
28+
}

0 commit comments

Comments
 (0)