Shortest Path Visiting All Nodes - Problem
You're given an undirected, connected graph with n nodes labeled from 0 to n-1. The graph is represented as an adjacency list where graph[i] contains all nodes directly connected to node i.
Your goal is to find the shortest path that visits every node at least once. This is a variation of the famous Traveling Salesman Problem!
Key Points:
- You can start and end at any node
- You can revisit nodes multiple times
- You can reuse edges
- Return the minimum number of edges in such a path
For example, if you have nodes [0,1,2] connected as 0-1-2, you need at least 2 edges to visit all nodes: either 0→1→2 or 2→1→0.
Input & Output
example_1.py — Simple Triangle
$
Input:
graph = [[1,2],[0,2],[0,1]]
›
Output:
2
💡 Note:
We have a triangle graph where all nodes are connected to each other. We can start at node 0, go to node 1 (1 edge), then go to node 2 (2 edges total). This visits all nodes in the minimum number of edges.
example_2.py — Linear Path
$
Input:
graph = [[1],[0,2],[1]]
›
Output:
2
💡 Note:
This is a linear path: 0-1-2. To visit all nodes, we need exactly 2 edges. We can start at either end (0 or 2) and traverse to the other end, visiting all nodes along the way.
example_3.py — Single Node
$
Input:
graph = [[]]
›
Output:
0
💡 Note:
With only one node and no edges, we're already visiting all nodes without moving anywhere. The shortest path length is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Smart State Tracking
Use a binary code to represent which landmarks you've visited - like a digital passport stamp
2
Systematic Exploration
Start from every landmark simultaneously, exploring layer by layer
3
Avoid Redundancy
Never revisit the same (location, visit-history) combination
4
First Complete Tour
The first time you visit all landmarks is guaranteed to be optimal
Key Takeaway
🎯 Key Insight: By combining BFS (for shortest path guarantee) with bitmask state representation (for efficient visit tracking), we solve this complex graph problem optimally without exploring redundant paths.
Time & Space Complexity
Time Complexity
O(n² × 2ⁿ)
We have n × 2^n possible states (n nodes × 2^n bitmasks), and for each state we check up to n neighbors
⚠ Quadratic Growth
Space Complexity
O(n × 2ⁿ)
We store up to n × 2^n states in our visited set and BFS queue
⚡ Linearithmic Space
Constraints
- 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code