n
(number of nodes), endingMask
(bitmask with all nodes visited), seen
(to prevent revisiting states), and queue
(for BFS).queue
and seen
with base cases: starting at each node with the mask set to having only visited that node.nextQueue
for the next step.
b. Loop through the current queue
, for each state (node, mask)
loop through graph[node]
.
c. For each neighbor, create a new state (neighbor, nextMask)
where nextMask = mask | (1 << neighbor)
.
d. If nextMask == endingMask
, return 1 + steps
as all nodes have been visited.
e. If the new state has not been visited, add it to nextQueue
and seen
.
f. Increment steps
and replace queue
with nextQueue
.endingMask
is encountered.