Shortest Path Visiting All Nodes - Problem

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.

Input & Output

Example 1 — Star Graph
$ Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
💡 Note: One shortest path: start at node 0, visit 0→1→0→2→0→3 (path length 4). All nodes are visited.
Example 2 — Linear Graph
$ Input: graph = [[1],[0,2],[1]]
Output: 2
💡 Note: Shortest path: 0→1→2 or 2→1→0 (path length 2). Visits all 3 nodes.
Example 3 — Single Node
$ Input: graph = [[]]
Output: 0
💡 Note: Only one node exists, so path length is 0 (already visited all nodes).

Constraints

  • n == graph.length
  • 1 ≤ n ≤ 12
  • 0 ≤ graph[i].length < n
  • graph[i] does not contain i
  • If graph[a] contains b, then graph[b] contains a
  • The input graph is always connected

Visualization

Tap to expand
Shortest Path Visiting All Nodes INPUT Graph Structure (Star Graph) 0 1 2 3 Adjacency List: graph[0] = [1, 2, 3] graph[1] = [0] graph[2] = [0] graph[3] = [0] n = 4 nodes ALGORITHM (BFS) 1 State: (node, visited_mask) Track which nodes visited 2 Initialize BFS Queue Start from each node 3 BFS Level Expansion Visit neighbors, update mask 4 Check Full Mask mask == (1 << n) - 1 = 15 BFS Traversal (from node 0): Step Node Mask Dist 0 0 0001 0 1 1 0011 1 2 0 0011 2 3 2 0111 3 4 0-->3 1111 4 mask=1111 means all 4 nodes visited! FINAL RESULT Optimal Path Found: 1 0 2 0 3 1 2 3 4 Path: 1 --> 0 --> 2 --> 0 --> 3 Total edges traversed: 4 Output: 4 OK - Shortest path length visiting all nodes! Key Insight: Use BFS with state (current_node, visited_bitmask) to find shortest path. The bitmask efficiently tracks which nodes are visited (bit i = 1 if node i visited). Target state: mask = 2^n - 1 (all bits set). Time: O(n * 2^n), Space: O(n * 2^n) for storing visited states. Nodes can be revisited! TutorialsPoint - Shortest Path Visiting All Nodes | BFS with Bitmask Approach
Asked in
Google 25 Facebook 18 Amazon 12
89.5K Views
Medium Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen