DSA Graphs

Shortest Path Visiting All Nodes

BFS over (node, visited-bitmask) states — return path length when the bitmask is all-ones.

Hard
Time O(2^n * n) Space O(2^n * n)
LeetCode
5 min read
bfs bitmask graph

Problem#

Given an undirected, connected graph on n nodes, return the shortest path that visits every node at least once. You can revisit nodes and edges and start anywhere.

Examples#

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

Constraints#

  • n == graph.length, 1 <= n <= 12.

Approach#

State = (currentNode, visitedBitmask). Multi-source BFS starting from every node with its own bit set. Pop a state, try every neighbor, set its bit, enqueue if unseen. Return the layer at which any state with bitmask (1<<n) - 1 is first popped.

Solution#

Shortest Path Visiting All Nodes
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
int n = graph.size();
int full = (1 << n) - 1;
vector<vector<bool>> seen(n, vector<bool>(full + 1, false));
queue<tuple<int,int,int>> q;
for (int i = 0; i < n; ++i) {
int mask = 1 << i;
q.push({i, mask, 0});
seen[i][mask] = true;
}
while (!q.empty()) {
auto [u, mask, d] = q.front(); q.pop();
if (mask == full) return d;
for (int v : graph[u]) {
int nm = mask | (1 << v);
if (!seen[v][nm]) {
seen[v][nm] = true;
q.push({v, nm, d + 1});
}
}
}
return 0;
}
};

Editorial#

The state space is n * 2^n, which fits easily at n = 12. Multi-source BFS handles “start anywhere” by initializing every node as a layer-0 state. Layer numbers correspond directly to path length.

Complexity#

  • Time: O(2^n * n^2) in the worst case (each state explores its neighbors).
  • Space: O(2^n * n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.