Visit Every Node Exactly Once: Path Existence in a Small Graph
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Decide whether an undirected graph of at most 20 vertices has a simple path through every vertex, which is best solved with a bitmask DP over visited subsets.
Visit Every Node Exactly Once
You are given an undirected graph with vertex_count vertices, labeled 0 to vertex_count - 1. The connections are listed in links, where each entry [a, b] is an undirected edge between vertex a and vertex b.
A full route is a sequence of vertices in which:
- every vertex of the graph appears exactly once, and
- every two consecutive vertices in the sequence are joined by an edge.
The route may start and end at any vertices. It does not need to return to its start.
Return True if the graph has at least one full route, and False otherwise.
Rules and edge cases
- If
vertex_countis0or1, returnTrue. - A self-loop (an edge
[a, a]) never helps a route and should be ignored. - Duplicate edges, including the same edge listed in both directions, are allowed and count as one connection.
- An edge with an endpoint outside
0 .. vertex_count - 1should be ignored. - A graph that is not connected, including one with an isolated vertex, has no full route.
Constraints
0 <= vertex_count <= 200 <= len(links), and each entry oflinkscontains exactly two integers.- Valid vertex labels are
0 .. vertex_count - 1. Entries with other labels are ignored as described above. - The function returns a boolean.
Examples
Example 1
Input: has_full_route(4, [[0, 1], [1, 2], [2, 0]])
Output: False
Hints
Hint 1
A route is built one vertex at a time. To extend it you need to know which vertices are already used and which vertex it currently ends at.
Hint 2
Since there are at most 20 vertices, represent the set of used vertices as a bitmask. For each mask, track which vertices can be the last vertex of a valid path covering exactly that mask.
Hint 3
Store the set of possible end vertices for each mask as a single integer bitmask. Store each vertex's neighbors the same way, so the unused neighbors of an endpoint are `neighbors[v] & ~mask`. A route exists exactly when the entry for the full mask is nonzero.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the Hamiltonian path problem, which is NP-complete, so an exponential algorithm is expected. The limit of 20 vertices points to a DP over subsets of vertices.
State. For every subset mask of vertices, keep ends[mask], a bitmask of the vertices v such that some simple path visits exactly the vertices in mask and finishes at v.
Base case. A single vertex is a path that ends at itself, so ends[1 << v] = 1 << v.
Transition. Take a mask and an end vertex v in ends[mask]. For every neighbor u of v that is not in mask, the path can be extended to u. So set bit u in ends[mask | (1 << u)].
Answer. A full route exists exactly when ends[(1 << n) - 1] is nonzero.
Implementation details.
- Neighbors are stored as bitmasks, so
adj[v] & ~maskgives all unvisited neighbors in one operation. - The end vertices of each mask are packed into one integer instead of a 2D boolean table. This cuts memory by a factor of
n. - Self-loops and out-of-range edges are skipped when building adjacency. Duplicate edges are absorbed by the bitwise OR.
n <= 1returnsTrueimmediately.
Why it is correct
- Soundness. By induction on the size of the mask, every bit recorded in
ends[mask]corresponds to a real simple path. Extensions only follow actual edges to vertices not yet used, so no vertex repeats. - Completeness. Any simple path through some set of vertices has all its prefixes as DP states. Each prefix is reached from the previous one by exactly one transition.
- Order.
mask | nbis numerically larger thanmaskwhenevernbis not inmask. Iterating masks in increasing order therefore finalizesends[mask]before it is used. - An isolated vertex can never be added to any path of more than one vertex, so the full mask stays at
0and the answer isFalse. The same holds for any disconnected graph.
Complexity
- Time: O(2^n * n^2) in the worst case. There are 2^n masks, up to n end vertices per mask, and up to n neighbors per end vertex. The bit tricks visit only endpoints and candidates that exist, so sparse graphs run much faster.
- Space: O(2^n) integers.
Reference solution
from typing import List
def has_full_route(vertex_count: int, links: List[List[int]]) -> bool:
n = vertex_count
if n <= 1:
return True
# Adjacency as bitmasks; skip self-loops and out-of-range endpoints.
adj = [0] * n
for a, b in links:
if 0 <= a < n and 0 <= b < n and a != b:
adj[a] |= 1 << b
adj[b] |= 1 << a
full = (1 << n) - 1
# ends[mask]: bitmask of vertices at which a path covering exactly `mask` can end.
ends = [0] * (1 << n)
for v in range(n):
ends[1 << v] = 1 << v
for mask in range(1 << n):
cur = ends[mask]
while cur:
low = cur & -cur
cur -= low
v = low.bit_length() - 1
free = adj[v] & ~mask
while free:
nb = free & -free
free -= nb
ends[mask | nb] |= nb
return ends[full] != 0