Shortest Path Visiting All Nodes solution explained
Shortest Path Visiting All Nodes is solved by breadth-first search over states of the form (current node, set of nodes visited so far), with the set stored as a bitmask. Start BFS from every node at once, each with only its own bit set, and the first time any state reaches the all-ones mask, its depth is the length of the shortest walk that covers the graph. With n nodes that is O(n² · 2^n) time.
By Evin JohnPublished 7 min read
The problem in plain words
You get an undirected, connected graph with n nodes labeled 0 to n - 1, as an adjacency list: entry i lists the neighbors of node i. Find the length of the shortest walk that visits every node at least once. Length means the number of edges traveled. The walk may begin at any node and end at any node, and it may pass through the same node or edge more than once.
| Adjacency list | Shape | Answer | One best walk |
|---|---|---|---|
| [[1], [0, 2], [1, 3], [2]] | A path of four nodes | 3 | 0, 1, 2, 3 |
| [[1, 2, 3], [0], [0], [0]] | A star with three leaves | 4 | 1, 0, 2, 0, 3 |
| [[1, 2], [0, 2], [0, 1, 3], [2]] | A triangle with a tail | 3 | 0, 1, 2, 3 |
| [[1], [0, 2, 4], [1, 3], [2], [1]] | A path with a side branch at node 1 | 5 | 0, 1, 4, 1, 2, 3 |
| [[]] | One node | 0 | Stand still |
The star shows why revisiting matters. No simple path covers all four nodes, so the best walk has to go back through the center. That rules out any approach that only considers simple paths, such as a Hamiltonian path search.
Slow approach: every visiting order
Any covering walk meets the nodes for the first time in some order. Between two consecutive first visits, the walk can do no better than the shortest path between those nodes. So compute all-pairs shortest distances with BFS from each node or Floyd-Warshall, then try every permutation of the n nodes and sum the distances between neighbors in the permutation. The minimum sum is the answer. It is a clean argument and a handy test oracle, but n! grows fast: 12 nodes give about 479 million orders.
Main approach: BFS over (node, visited mask)
Ask what you really need to know at any moment of the walk. Only two things: where you are, and which nodes you have already seen. The order of earlier visits does not affect what you can do next. That pair is the state. Store the visited set as an n-bit integer, where bit i means node i has been visited. Moving along an edge to node u costs 1 and sets bit u.
Since every move costs the same, BFS over these states finds the fewest moves to any state. You also do not know the best starting node, so seed the queue with all n of them: state (v, 1 << v) at distance 0 for each v. This multi-source start is equivalent to trying every starting node, in one search.
- Handle the trivial graphWith zero or one node, return 0.
- Seed every nodePush (v, 1 << v, 0) for each node and mark those states seen.
- Expand along edgesFor a popped state (v, mask, d), visit each neighbor u and compute mask | (1 << u).
- Return on a full maskIf the new mask has all n bits set, return d + 1. Otherwise push the state if it is new.
from collections import deque
def shortest_tour(graph):
n = len(graph)
if n <= 1:
return 0
full = (1 << n) - 1
queue = deque((v, 1 << v, 0) for v in range(n))
seen = {(v, 1 << v) for v in range(n)}
while queue:
v, mask, d = queue.popleft()
for u in graph[v]:
nmask = mask | (1 << u)
if nmask == full:
return d + 1
if (u, nmask) not in seen:
seen.add((u, nmask))
queue.append((u, nmask, d + 1))
return -1function shortestTour(graph) {
const n = graph.length;
if (n <= 1) return 0;
const full = (1 << n) - 1;
const seen = Array.from({ length: n }, () => new Uint8Array(1 << n));
const queue = [];
for (let v = 0; v < n; v++) {
seen[v][1 << v] = 1;
queue.push([v, 1 << v, 0]);
}
for (let head = 0; head < queue.length; head++) {
const [v, mask, d] = queue[head];
for (const u of graph[v]) {
const next = mask | (1 << u);
if (next === full) return d + 1;
if (!seen[u][next]) {
seen[u][next] = 1;
queue.push([u, next, d + 1]);
}
}
}
return -1;
}The final return -1 only runs if the graph is disconnected, which the usual statement rules out. Keeping it makes the function honest on bad input. Trace the star: the first wave reaches states like (0, mask of 0 and 1) from leaf 1. The second wave goes back out to leaf 2, the third returns to the center, and the fourth reaches leaf 3 with every bit set, so the answer is 4.
Complexity
| Approach | Time | Space |
|---|---|---|
| Every visiting order over all-pairs distances | O(n · E + n! · n) | O(n²) |
| BFS over (node, mask) | O(2^n · E), at most O(n² · 2^n) | O(n · 2^n) |
| DP over subsets with all-pairs distances | O(n² · 2^n) | O(n · 2^n) |
Each of the n · 2^n states is processed once, and each processing looks at the node's neighbors. Summed over all nodes for a fixed mask that is O(E) work, giving O(2^n · E). For n = 12 there are 12 · 4,096 = 49,152 states, which is tiny. The approach collapses quickly beyond about 20 nodes, so state that limit when you present it.
The subset DP in the last row is the Held-Karp idea from the traveling salesman problem: dp[mask][v] is the shortest walk that has visited mask and ends at v, filled from smaller masks using precomputed distances. It reaches the same bound; BFS is usually shorter to write because edge weights are all 1.
Edge cases to test
- A single node with no edges: return 0.
- Two nodes joined by one edge: return 1.
- A path, where the answer is n - 1 and no revisits are needed.
- A star, where every extra leaf costs two more moves.
- A complete graph, where any order works and the answer is n - 1.
- Twelve nodes, to confirm the state count and memory stay reasonable.
Common mistakes
- Using a visited set over nodes only. Revisiting a node with a larger mask is progress and must be allowed.
- Starting BFS from node 0 only. The best walk might start at a leaf elsewhere.
- Counting nodes instead of edges, which gives an answer that is one too high.
- Searching only simple paths, which fails on stars and trees with branches.
- Allocating a seen table of n by 2^n as a nested list of booleans in a slow language without noticing the size; it is fine at n = 12 but worth stating.
Presenting the idea
Fictional example
- Candidate
- Revisits are allowed, so a normal visited set on nodes won't work. What matters is where I am and which nodes I've covered, so my state is the node plus a bitmask.
- Candidate
- Every edge costs one, so BFS over those states gives the minimum. I don't know where to start, so I put all n starting states in the queue together.
- Interviewer
- How big does that get?
- Candidate
- n times 2 to the n states. With 12 nodes that's about forty-nine thousand, so it's fast. It would not scale to 30 nodes.
Related problems in this set
The bitmask-in-the-state idea first appears in this set in Shortest Path to Get All Keys, where the mask tracks keys picked up on a grid. Single-source grid BFS with an early stop is covered in Nearest Exit from Entrance in Maze, and graph search with layers and parent links in Word Ladder II. For bitmasks and graph representations in general, see the data structure interview questions.
Rehearsing it with Natively
State-design problems like this are best practiced aloud. Natively transcribes a mock round on your own computer, so afterwards you can see whether you defined the state before you started typing. In practice it can also read the graph prompt from a screenshot and suggest a plan to compare with yours. The AI interview assistant page describes how this works on Mac and Windows.
Questions people ask
How do you solve Shortest Path Visiting All Nodes?
Use BFS where each state is the current node and a bitmask of visited nodes. Seed the queue with every node and its own bit, expand along edges, and return the depth when a mask with all bits set appears.
Why start the BFS from every node?
The best walk can start anywhere. Putting all n starting states in the queue together is the same as trying every start, in a single search.
What is the time complexity?
There are n · 2^n states, and expanding all of them costs O(2^n · E), which is at most O(n² · 2^n). That is fast for n up to about 12 and impractical much beyond 20.
Can the walk revisit nodes?
Yes, and it often must. In a star graph the walk has to pass back through the center, which is why a visited set over nodes alone gives wrong answers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
