Shortest path visiting all nodes
Standard · Write code · about 18 min
graph[i] lists the neighbours of node i in a connected, undirected graph. You may start at any node, move along edges, and revisit nodes and edges as often as you like.
Return the fewest moves that visit every node at least once.
Example 1
Input:
[[[1,2,3],[0],[0],[0]]]
Output:
4
Start at leaf 1: 1 → 0 → 2 → 0 → 3 is 4 moves.
Example 2
Input:
[[[1],[0,2,4],[1,3,4],[2],[1,2]]]
Output:
4
0 → 1 → 4 → 2 → 3 is 4 moves.
Constraints
- 1 ≤ graph.length ≤ 12
- graph[i] does not contain i; edges are listed in both directions
- The graph is connected
Learn the idea first: Bitmask DP: TSP and assignments, a visual lesson.
More Bitmask DP: TSP and assignments problems
- Which mask is it? Warm-up
- Fill the trip table Warm-up
- Minimum cost assignment Standard
- Count valid subsets Standard