697. Visit Every Node

A delivery drone must inspect n towers numbered 0 to n - 1, joined by cables. The array graph is an adjacency list: graph[i] lists every tower directly cabled to tower i. The cabling is undirected and connected, has no self-loops and no repeated cables.

The drone may start at any tower and end at any tower. Each step moves along one cable, and towers and cables may be used any number of times. Return the minimum number of steps for a flight that visits every tower at least once. For a single tower the answer is 0. Because n is small, a search over states (set of visited towers, current tower) solves it in O(2^n * n * n) time.

Example 1

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

Starting at tower 4, the drone goes 4, 3, 0, 1, 2: four steps visit all five towers, and no shorter flight can visit every tower.

Example 2

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

A star with four leaves: the drone must return to the centre between leaves, e.g. leaf, centre, leaf, centre, leaf, centre, leaf: 6 steps.

Example 3

Input:
graph = [[1],[0,2],[1]]
Output:
2
Explanation:

On the path 0-1-2 start at one end and walk to the other: 2 steps.

Constraints

1 ≤ n ≤ 12

graph[i] contains each neighbour of i exactly once, and i is never listed in graph[i].

If j is in graph[i] then i is in graph[j]; the graph is connected.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^n * n^2)
Space
O(2^n * n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…