Towers of Hanoi

The Towers of Hanoi is one of the great, canonical puzzles used in teaching recursive programming solutions.

Source: https://commons.wikimedia.org/wiki/File:Iterative_algorithm_solving_a_6_disks_Tower_of_Hanoi.gif

Here’s a video that describes the problem and its solution.

Python implementation

Here’s an implementation in Python

"""
  Towers of Hanoi solver
"""

def towers_of_hanoi(n, origin, destination, auxiliary):
    if n == 1:
        print(f"Move disk 1 from {origin} to {destination}")
        return
    # Move n-1 disks from origin to auxiliary
    towers_of_hanoi(n - 1, origin, auxiliary, destination)
    print(f"Move disk {n} from {origin} to {destination}")
    # Move n-1 disks from auxiliary to destination
    towers_of_hanoi(n - 1, auxiliary, destination, origin)

# Example usage: 3 disks
n = 3
towers_of_hanoi(n, 'A', 'C', 'B')

Prolog implementation

Make sure you understand the recursive solution in Python first. Once you’re certain you know how it works, give it a try in Prolog.

/**
  Towers of Hanoi solver
*/

% Base case: Move one disk directly from origin to destination
move(1, Origin, Destination, _) :-
    format('Move disk 1 from ~w to ~w.', [Origin, Destination]), nl.

% Recursive case: Move N disks from origin to destination using auxiliary
move(N, Origin, Destination, Auxiliary) :-
    N > 1,
    M is N - 1,
    move(M, Origin, Auxiliary, Destination),
    format('Move disk ~w from ~w to ~w.', [N, Origin, Destination]), nl,
    move(M, Auxiliary, Destination, Origin).

% Start the process with move(N, 'A', 'C', 'B') assuming A, B, and C are spindles
hanoi(N) :- move(N, 'A', 'C', 'B').

% For a solution, consult this file, and run a query indicating the
% number of disks, e.g., `?- hanoi(5).`


Here’s a somewhat different solution from one of the standard texts on Prolog.


Copyright © 2023–2026 Clayton Cafiero

No generative AI was used in producing drafts of this material. This was written the old-fashioned way. AI was used to rewrite existing pseudocode in LaTeX to produce standalone *.tex files for rendering, and for revisions toward satisfying WCAG 2.1 AA-level accessibility standards as required by UVM policy. It may also have been used to proofread selected human-written prose. Claude 2.1.150 with model Sonnet 4.6. Revisions, if any, were performed by the author. AI was not used in generating any code whatsoever. All code samples and starter code are by the author only.