Shortest walk visiting every vertex
Return the fewest edges in a walk visiting every vertex of an undirected graph represented by adjacency lists. Start anywhere, revisit vertices if needed, and return -1 if disconnected. Empty graph returns zero.
mask = 0b0011
next_node = 2
print(bin(mask | (1 << next_node)))Reason about the state
Run a multi-source breadth-first search over pairs of current vertex and visited bitmask. The mask distinguishes visits with different remaining work. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the fewest edges in a walk visiting every vertex of an undirected graph represented by adjacency lists. Start anywhere, revisit vertices if needed, and return -1 if disconnected. Empty graph returns zero.
The explanation opens here once every check passes.