Solution

ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2016/functional-programming-design-and-analysis-of-algorithms/6/b/solution

Use subset dynamic programming for a Hamiltonian path, with a Boolean dynamic programming state for each nonempty subset and . It is true exactly when there is a graph path using every vertex of once, using no other vertices, and ending at . The base and transition are
where is the adjacency matrix of a directed graph.
HamiltonianExists(A):
    initialize every D[S,v] to false
    for v in V:
        D[{v},v] = true
    for k = 2,...,n:
        for S subset of V with |S| = k:
            for v in S:
                D[S,v] = any(D[S-{v},u] and A[u,v]
                             for u in S-{v})
    return any(D[V,v] for v in V)
For correctness, a valid path ending at has some penultimate vertex ; removing yields exactly a path recorded by the corresponding predecessor state. Conversely, extending any true predecessor state by the edge produces a path visiting precisely once. Mathematical induction on proves the meaning of every state. Therefore the final disjunction is true exactly when a Hamiltonian path exists.
There are possible states and at most predecessor checks per state. More exactly, the full set of ordered predecessor checks has size for . With constant-time adjacency matrix access and ordinary subset-indexed table access,
The graph is normally assumed nonempty here. If the empty graph is admitted, return the chosen convention for its empty Hamiltonian path separately; it does not affect the bound.

New to topics? Read the docs here!