#847

Shortest Path Visiting All Nodes

Hard BFS over (node, visited-mask)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a connected undirected graph with n ≤ 12 nodes, return the length of the shortest walk that visits every node (you can start and end anywhere and reuse nodes and edges).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the shortest walk that visits every node.

Why this works: the state is (current node, set of visited nodes). BFS over those states finds the shortest walk.

Example: star graph 0 connected to 1, 2, 3

1 → 0 → 2 → 0 → 3 → 4 steps

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Marking only nodes as visited — you must be allowed to revisit a node with a different mask.

Solve on LeetCode ↗
Complexity
  • Time: O(n² · 2^n).
  • Space: O(n · 2^n).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon