Example 1
- Input
- graph = [[1,2,3],[0],[0],[0]]
- Output
- 4
Walk 1 → 0 → 2 → 0 → 3 visits every vertex in four edges. Three leaves require two passages through the center between leaf visits, so three edges cannot suffice.
Find the fewest edge traversals needed to visit every vertex of a connected undirected graph. Choose any starting and ending vertices; vertices and edges may be used repeatedly.
Given an adjacency list graph for a connected undirected graph whose vertices are numbered from 0 to n - 1, return the length of a shortest walk visiting every vertex. Length counts traversed edges, not distinct vertices. You may start and finish anywhere, revisit a vertex, and traverse an edge more than once.
The official problem calls this a path, but repeated vertices are explicitly allowed. A Hamiltonian path, which visits each vertex exactly once, is not required.
n == graph.length and 1 <= n <= 12.0 <= graph[i].length < n; a vertex is not its own neighbor.b is in graph[a], then a is in graph[b].Walk 1 → 0 → 2 → 0 → 3 visits every vertex in four edges. Three leaves require two passages through the center between leaf visits, so three edges cannot suffice.
Walk 0 → 1 → 4 → 2 → 3 uses four edges. Visiting five distinct vertices requires at least four edges, so this walk attains the lower bound.
The starting vertex already covers the whole graph. No edge needs to be traversed.
Remember both where the walk ends and which vertices it has already visited. A bitmask stores that visited set: bit v is one exactly when vertex v has been seen. In Example 1, the star cannot be covered without returning through its center: 1 → 0 → 2 → 0 → 3 takes four edges. Reaching vertex 0 with mask 0011 is a different state from reaching it with mask 0111; the second walk has already covered another leaf. The mask never loses bits, but a move can leave it unchanged, so a simple increasing-mask DP loop cannot settle every distance. Breadth-first search settles the minimum distance to each state instead.
Reveal Bitmask BFS: intuition, complexity, and code
(node, mask) as an unweighted search state.2n - 4.shift() on the queue repeatedly adds array movement; use the head index shown.When future choices depend on a small visited subset, expand the graph state to include that subset. Cyclic transitions within a mask need shortest-path exploration rather than assuming subset size alone orders the DP.