AlgoInsight

DSA problem

Shortest Path Visiting All Nodes

HardBitmask DPPattern: Bitmask DPtop75GoogleAmazonMicrosoftMetaApple

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. There are no self-loops or multi-edges.

Because the answer permits revisits, this is not a Hamiltonian path question — it is asking for the shortest walk that touches every node. We are free to choose any start, and intermediate nodes may repeat. The set of nodes already visited is what matters for future progress, not the exact path taken to reach them, so we need a state that captures (current node, visited set).

The natural encoding is a bitmask: visited is an n-bit integer whose i-th bit is set if node i has been touched. Together with the current node, the state space has size n * 2^n, which is tractable for n <= 12 (about 49152 states).

Because every edge has unit weight, BFS finds the shortest path. We initialize the BFS queue with every starting state (i, 1 << i) for i in 0..n - 1 (any node can be the start), each at distance 0. Each transition pops (u, mask) and pushes (v, mask | (1 << v)) for every neighbour v, incrementing the distance by 1. The first time we pop a state whose mask equals (1 << n) - 1 (every node visited), its distance is the answer. The visited[node][mask] table prevents revisiting states. Time and space are both O(n * 2^n).

Examples

Example 1
Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: A possible path is 1 -> 0 -> 2 -> 0 -> 3 with length 4; node 0 is the hub, and any walk visiting all leaves needs at least 4 edges.
Example 2
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: Path 0 -> 1 -> 4 -> 2 -> 3 visits every node in exactly 4 edges.
Example 3
Input: graph = [[1],[0]]
Output: 1
Explanation: Two nodes connected by one edge: walk from 0 to 1 in 1 step covers all nodes.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dynamic-programmingbitmaskbfsgraph

Browse all DSA problems