Shortest Path Visiting All Nodes Solution
Find the minimum number of edges needed to visit every node in an undirected graph. You may start at any node, revisit nodes, and reuse edges.
Problem Statement
Because revisits are allowed, the real state is not just βwhich node am I on?β It is:
where visitedMask marks which nodes have been seen so far. The target is any state whose mask has all bits set.
Backtracking Over State Space β Exponential
A brute-force strategy is to recursively try every walk, remember the set of visited nodes, and keep the minimum length once all nodes have been seen.
If we enumerate every possible walk, then eventually we discover the shortest walk that covers all nodes.
(node, mask). From that point onward, the future possibilities are identical. BFS over these deduplicated states is dramatically better and automatically gives the shortest number of edges because the graph is unweighted.Multi-source BFS on (node, mask) States β O(V Β· 2^V)
Start BFS simultaneously from every node, because the problem lets us choose any start. The initial states are (i, 1 << i) for all nodes i. From a state (u, mask), moving to neighbor v gives the next state (v, mask | (1 << v)).
- Let
finalMask = (1 << n) - 1. - Initialize the queue with all
nstarting states. - Use
visited[node][mask]to avoid reprocessing the same state. - For each BFS move, update the mask with the destination node bit.
- The first state reaching
finalMaskgives the shortest path length.
- When the prompt asks to βvisit all nodes / collect all keys / cover all subsetsβ with an unweighted graph, think BFS on position + bitmask.
- The node alone is not enough state.
Visual Walkthrough
Trace graph = [[1,2,3],[0],[0],[0]].
Code β Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Backtracking state search | Explosive / exponential | O(V) recursion + visited set | Repeatedly solves the same subproblems. |
| BFS on (node, mask) β optimal | O(V Β· 2^V + E Β· 2^V) | O(V Β· 2^V) | Every unique state is processed at most once. |
Edge Cases & Pitfalls
| Case | Expected behavior | Why it matters |
|---|---|---|
| Single-node graph | Return 0 | All nodes are already visited. |
| Any start allowed | Use multi-source BFS | Starting from only one node can miss the optimal route. |
| Revisiting nodes | Allowed and often necessary | Do not use a simple visited-node set. |
| State deduplication | Use visited[node][mask] | Same node with different masks are different states. |
| Stopping condition | Check mask == finalMask | Visiting all nodes matters, not arriving at one special destination. |
visited[node]. That loses essential information. Reaching node 3 after visiting 3 is completely different from reaching node 3 after visiting 3. The mask must be part of the state.