847. Shortest Path Visiting All Nodes
Description
You have an undirected, connected graph of n
nodes labeled from 0
to n - 1
. You are given an array graph
where graph[i]
is a list of all the nodes connected with node i
by an edge.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
Example 1:
Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3]
Example 2:
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3]
Constraints:
n == graph.length
1 <= n <= 12
0 <= graph[i].length < n
graph[i]
does not containi
.- If
graph[a]
containsb
, thengraph[b]
containsa
. - The input graph is always connected.
Solutions
Solution: Breadth-First Search + Bitmask
- Time complexity: O(n*2n)
- Space complexity: O(n*2n)
JavaScript
js
/**
* @param {number[][]} graph
* @return {number}
*/
const shortestPathLength = function (graph) {
const n = graph.length;
const fullAccess = (1 << n) - 1;
const seen = new Array(n)
.fill('')
.map(_ => Array.from({length: 1 << n}).fill(false));
let queue = [];
let result = 0;
for (let index = 0; index < n; index++) {
const visited = 1 << index;
queue.push({ node: index, visited });
seen[index][visited] = true;
}
while (queue.length) {
const nextQueue = [];
for (const { node, visited } of queue) {
for (const next of graph[node]) {
const nextVisited = visited | (1 << next);
if (nextVisited === fullAccess) return result + 1;
if (seen[next][nextVisited]) continue;
nextQueue.push({ node: next, visited: nextVisited });
seen[next][nextVisited] = true;
}
}
result += 1;
queue = nextQueue;
}
return 0;
};