KatInterview

Visit Every Node Exactly Once: Path Existence in a Small Graph

Dynamic ProgrammingAuto-graded · 17 test cases
HardAuto-gradedDynamic Programmingbitmask-dpgraphhamiltonian-path

Last 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_count is 0 or 1, return True.
  • 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 - 1 should be ignored.
  • A graph that is not connected, including one with an isolated vertex, has no full route.

Constraints

  • 0 <= vertex_count <= 20
  • 0 <= len(links), and each entry of links contains 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.