Problem 625
Shortest Path Visiting All Nodes
Hard · 30 pts · Graph, Breadth-First Search, Bitmask
Problem
You are given a connected undirected graph with N nodes. Find the length of the shortest walk that visits every node at least once. You may start and end at any node, revisit nodes, and reuse edges; the length is the number of edges travelled. With N at most 12, run a breadth-first search over states (current node, set of visited nodes as a bitmask), starting from every node at once; the first state whose mask contains all nodes gives the answer.
Input
The first line contains N and M. Each of the next M lines contains an edge u v (nodes are numbered from 1).
Output
Print the length of the shortest walk visiting all nodes.
Constraints
1 <= N <= 12; 0 <= M <= N × (N - 1) / 2; the graph is connected
Example input
4 3 1 2 1 3 1 4
Example output
4
Explanation
In the star graph with centre 1 and leaves 2, 3 and 4, one shortest walk is 2 → 1 → 3 → 1 → 4. It has 4 edges, and every walk covering all leaves needs at least that many.