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 → Process → OutputInput Graph0123[[1,2,3],[0],[0],[0]]BFS + BitmaskState: (node, visited)Track all node subsetsFind shortest pathOutput4Path lengthExample path: 0 → 1 → 0 → 2 → 0 → 3 (length = 4)🎯 Key Insight: Use BFS with bitmasks to efficiently track visited node combinations
Understanding the Visualization
1
Input Graph
Undirected connected graph as adjacency list
2
Find Path
Find shortest path that visits every node
3
Output Length
Return the path length (number of edges)
Key Takeaway
🎯 Key Insight: Use BFS with bitmasks to represent visited nodes as states, guaranteeing the shortest path while avoiding exponential path enumeration
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