1
/**
2
* @param {number[][]} graph
3
* @return {number}
4
*/
5
var shortestPathLength = function (graph) {
6
const n = graph.length;
7
const allVisited = (1 << n) - 1;
8
const queue = [];
9
const visited = new Set();
10

11
for (let i = 0; i < n; i++) {
12
queue.push([1 << i, i, 0]);
13
visited.add((1 << i) * 16 + i);
14
}
15

16
while (queue.length > 0) {
17
const [mask, node, dist] = queue.shift();
18

19
if (mask === allVisited) {
20
return dist;
21
}
22

23
for (const neighbor of graph[node]) {
24
const newMask = mask | (1 << neighbor);
25
const hashValue = newMask * 16 + neighbor;
26

27
if (!visited.has(hashValue)) {
28
visited.add(hashValue);
29
queue.push([newMask, neighbor, dist + 1]);
30
}
31
}
32
}
33

34
return -1;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0