Shortest Path Visiting All Nodes

Hard · Graphs · Dynamic Programming · Bit Manipulation · Breadth-First Search · Graph · Bitmask

Problem

You have an undirected, connected graph of n nodes labeled 0 to n - 1, given as an adjacency list graph where graph[i] lists the neighbors of node i.

Return the length (number of edges) of the shortest walk that visits every node at least once. You may start and end at any node, revisit nodes, and reuse edges.

Examples

Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4

Start at a leaf: 1-0-2-0-3 is four edges.

Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4

One shortest walk is 0-1-4-2-3.

Input: graph = [[]]
Output: 0

The only node is visited at the start.

Constraints

Approaches

Follow-up

The state space has n · 2^n states, about 49,000 for 12 nodes, which is why n is kept small: the problem is a shortest Hamiltonian-path relative. The use cases ask for a closed walk (a bitmask DP over all-pairs distances) and for visiting only some required nodes from a fixed start.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…