← Back to Visualizer Gallery
Traversal · State-Space BFS + Bitmask LeetCode 847

Shortest Path Visiting All Nodes / multi-source BFS

Revisiting nodes is required. The state is $(u, \text{mask})$ where $u$ is the active vertex and $\text{mask}$ represents visited nodes. Seed all $n$ nodes simultaneously into BFS to find the global minimum path.

Execution Stage

idle
INVARIANT Multi-Source BFS Invariant: We seed all $n$ nodes simultaneously at step 0 with bitmask $(1 \ll i)$. A node $v$ may be revisited multiple times if and only if the bitmask expands ($\text{mask}' = \text{mask} \mid (1 \ll v)$).
Path Length 0
Active Mask 0b0000
Target Mask 0b1111
Press Run to trace multi-source bitmask BFS.
0 / 0
Speed

Java · Reference Algorithm

INTERVIEW SCRIPT

How to Present Shortest Path Visiting All Nodes to an Interviewer

1. Multi-Source Seeding

"Any node in the graph could serve as the optimal starting point. Therefore, we seed all $N$ nodes into our BFS queue simultaneously at step 0 with their respective initial bitmasks $(1 \ll i)$."

2. State Definition $(u, \text{mask})$

"Because we are permitted to revisit nodes and edges, the state must pair the current vertex $u$ with the set of all vertices visited so far, represented as a bitmask."

3. Target Condition

"When we pop a state where $\text{mask} == (1 \ll N) - 1$, all $N$ nodes have been covered. Because BFS proceeds level by level, this first occurrence is guaranteed to be the shortest path."

4. Complexity Bound

"There are $N \cdot 2^N$ total states. For $N \le 12$, $12 \cdot 4096 \approx 49,152$ states. Each state transitions to its neighbors in $O(1)$ time, yielding $O(N^2 \cdot 2^N)$ total runtime."

Shortest Path Visiting All Nodes (LC 847) — Multi-source bitmask BFS · Time $O(N^2 \cdot 2^N)$, Space $O(N \cdot 2^N)$.