Problem Description
Given an undirected, connected graph of n nodes, where nodes are labeled from 0 to n-1 and graph[i] contains all nodes adjacent to i, find the length of the shortest path that visits every node. You may start and end at any node, revisit nodes, and re-use edges.
Key Insights
- The problem is a variant of the Traveling Salesman Problem, but the small constraint (n ≤ 12) permits a solution using bitmasking.
- Each state can be represented as a combination of the current node and a bitmask indicating which nodes have been visited.
- Breadth-first search (BFS) helps guarantee that the first time we encounter a state with all nodes visited, it is via the shortest path.
- Using multi-source BFS from each node as a starting point simplifies the logic because we can start from any node.
Space and Time Complexity
Time Complexity: O(n * 2^n) where n is the number of nodes since we potentially visit each state (node, visited-mask) once. Space Complexity: O(n * 2^n) for storing the states in the visited set and the BFS queue.
Solution
The solution uses a BFS that expands states of the form (current node, visited mask). Initially, every node is added to the queue with its corresponding bitmask. At each BFS step, we iterate over all adjacent nodes and update the visited mask by setting the bit corresponding to the neighbor. When the visited mask equals (1 << n) - 1 (all nodes visited), we return the number of steps taken. This BFS expansion ensures that we always find the shortest path.