07. Shortest Path Visiting All Nodes
You have an undirected connected graph of n nodes. Return the length of the shortest path that visits every node.
How It Works & Algorithmic Design
Solves using BFS State Traversal with Bitmasking:
- State Definition: Queue stores
(node, bitmask, distance). - Target Bitmask: Goal mask =
(1 << n) - 1. - Queue Initialization: Push all nodes
(i, 1 << i, 0)into queue (allowing search to begin from any arbitrary node). - BFS Step:
- Pop
(curr, mask, dist). - If
mask === targetMask, returndist. - For each neighbor in
graph[curr]:newMask = mask | (1 << neighbor).- If state
(neighbor, newMask)is unvisited, mark visited and push to queue.
- Pop
Why This Approach Works Best
BFS guarantees shortest path distance while bitmasking compresses graph visitation states in $O(n \cdot 2^n)$ time.
Example Walkthrough
Input Graph
[[1,2,3],[0],[0],[0]]
4 node star graph.
Optimal Route
1 -> 0 -> 2 -> 0 -> 3 (4 total edge steps).
Visits all nodes.
Output
4
Shortest path length.
Answer: Shortest Path Visiting All Nodes implementation
function shortestPathLength(graph) {
const n = graph.length;
const targetMask = (1 << n) - 1;
const queue = [];
const visited = new Set();
for (let i = 0; i < n; i++) {
const mask = 1 << i;
queue.push([i, mask, 0]);
visited.add(`${i},${mask}`);
}
while (queue.length) {
const [node, mask, dist] = queue.shift();
if (mask === targetMask) return dist;
for (const neighbor of graph[node]) {
const nextMask = mask | (1 << neighbor);
const state = `${neighbor},${nextMask}`;
if (!visited.has(state)) {
visited.add(state);
queue.push([neighbor, nextMask, dist + 1]);
}
}
}
return 0;
}BFS search tracking visited nodes via bitmask to find shortest path covering all graph vertices.
Key Takeaways
Initialize BFS with all nodes to test every starting point.
Bitmask state representation compresses node visitation sets.
Runs in $O(n \cdot 2^n)$ time.