2-D Dynamic Programming Bitmask DP
600. Shortest Path Visiting All Nodes
You are given an undirected, connected graph with n nodes, numbered from 0 to n - 1. graph[u] lists
every node that shares an edge with node u. An edge works in both directions, so v is in graph[u]
exactly when u is in graph[v].
A walk moves from node to node along edges, one edge at a time. Return the length of the shortest walk that visits every node at least once. The length of a walk is the number of edges it moves along.
The walk can start and end at any nodes. It may pass through a node or use an edge more than once.
Example 1
Input: graph = [[1, 2, 3],
[0, 2, 4],
[1, 0, 5],
[0],
[1],
[2, 6],
[5]]
7Explanation: One shortest walk is 3 → 0 → 1 → 4 → 1 → 2 → 5 → 6. Nodes 3, 4 and 6 each have one neighbour, and a walk can start or end at only two of them, so it must come back out of the third.
Example 2
Input: graph = [[1, 2, 3], [0], [0], [0, 4, 5], [3], [3]]
7Explanation: One shortest walk is 1 → 0 → 2 → 0 → 3 → 4 → 3 → 5. A walk that starts at node 0 needs at least 8 edges.
Example 3
Input: graph = [[]]
0Explanation: The only node is visited where the walk starts, so the walk needs no edges.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n == graph.length ≤ 160 ≤ graph[u][i] < ngraph[u]does not containu.- The values in
graph[u]are distinct. - If
graph[u]containsv, thengraph[v]containsu. - The graph is connected.
Clarifying questions
What you would ask an interviewer before writing any code.