Sometimes the history is a set you cannot forget
Picture
You must visit every vertex exactly once. Knowing only your current vertex loses which vertices remain legal. Different visit orders can still share a continuation if they have the same current vertex and the same visited set. A bitmask is a compact way to represent that set.
Predict
Two routes reach vertex 3. One has visited {0,1,3}, the other {0,2,3}. May their remaining route counts share a key containing only 3?
Reveal the reasoning
No. One can still visit 2, while the other can still visit 1. The visited set changes future legality. Equal set and current vertex would be sufficient under the fixed edge rules here.
Go deeper: compress representation, not information
For vertices 0..n-1, bit v is set when v has been visited. mask & (1 << v) checks membership; mask | (1 << v) includes the vertex. Count vertex sequences that start at 0 and visit all vertices exactly once; the endpoint is unrestricted. Assume n>=1, valid labels, and no duplicate neighbors.
from functools import cache
def complete_routes(graph):
n = len(graph)
all_seen = (1 << n) - 1
@cache
def ways(node, mask):
if mask == all_seen:
return 1
return sum(ways(v, mask | (1 << v))
for v in graph[node] if not mask & (1 << v))
return ways(0, 1)
assert complete_routes([[1, 2], [0, 2], [0, 1]]) == 2
assert complete_routes([[1], [], []]) == 0
assert complete_routes([[]]) == 1
The two triangle routes are 0→1→2 and 0→2→1. This does not require returning to the start. Adding that requirement changes the terminal condition.
There are at most n·2**n states, each inspecting up to n neighbors: O(n²·2**n) time and O(n·2**n) cached space, plus O(n) stack depth. This can improve on enumerating every ordering, but remains exponential. A bitmask stored in one integer does not make the state space one small linear dimension.
Analogy limit: “compress” here means encode a set compactly. It does not justify forgetting its members or turning an exponential problem into a polynomial one.
Change one rule
You only need to know whether the destination is reachable, and revisits are allowed. Must a visited-set mask remain part of every logical vertex?
Check the variation
No. For a fixed graph, ordinary reachability needs only the graph vertex as the search state and a global discovered set to avoid repeated exploration. The exactly-once route constraint created the exponential state requirement.
Connect
Backtracking is a useful baseline for tiny instances. Cost estimation prevents mistaking a compact key for a small search. Recognition connects the output contract to required history.