Skip to content
BytePatterns

Shortest Walk Through Every Node

HardBit Manipulation#bitmask#bfs~45m

Problem

A connected undirected graph has n nodes, numbered 0 to n - 1, where n is at most 12, given as adjacency lists. Return the fewest edges in a walk that visits every node at least once. The walk may start and end at any nodes, and it may repeat both nodes and edges.

Examples

Input:  adj = [[1, 3, 4], [0, 2], [1, 3, 5], [2, 0], [0], [2]]
Output: 6
Why:    a square 0-1-2-3 with a leaf on 0 and a leaf on 2;
        4-0-1-2-3-2-5 has to step back through 2 once
Input:  adj = [[1, 2], [0, 2, 5], [0, 1, 3], [2, 4], [3], [1]]
Output: 5
Why:    5-1-0-2-3-4 touches all six nodes without repeating one
Input:  adj = [[]]
Output: 0
Why:    edge case, a single node is visited before any step is taken

Hints

0 / 3

Stuck on the idea rather than the code? Bitmask as a Set covers it.