oneby7

2-D Dynamic Programming Bitmask DP

600. Shortest Path Visiting All Nodes

Hard

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

0123456

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

Output: 7

Explanation: 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

012345

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

Output: 7

Explanation: 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

0

Input: graph = [[]]

Output: 0

Explanation: 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.

graph = [[1, 2, 3, 4], [0], [0], [0], [0]]

Constraints

  • 1 ≤ n == graph.length ≤ 16
  • 0 ≤ graph[u][i] < n
  • graph[u] does not contain u.
  • The values in graph[u] are distinct.
  • If graph[u] contains v, then graph[v] contains u.
  • The graph is connected.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.