Tower of Hanoi

The Tower of Hanoi is a puzzle in which the objective is to move a stack of disks from one rod to another, obeying certain rules. This problem asks for the sequence of moves required to solve the puzzle for a given number of disks.


The Tower of Hanoi is a puzzle consisting of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
- No larger disk may be placed on top of a smaller disk.
Print the sequence of moves required to solve the Tower of Hanoi puzzle for n disks.
1 -> 3
1 -> 2
3 -> 2
1 -> 3
2 -> 1
2 -> 3
1 -> 3


This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Solution:

# The optimal solution is to move the top n-1 disks to the middle rod, then move the bottom disk to the last rod, then move the n-1 disks to the last rod.
# This is optimal because it is the minimum number of moves required to move n disks.

def tower_of_hanoi(n, source, destination, aux):
    if n == 1:
        print(source, "->", destination)
    tower_of_hanoi(n-1, source, aux, destination)
    print(source, "->", destination)
    tower_of_hanoi(n-1, aux, destination, source)

n = int(input())
tower_of_hanoi(n, 1, 3, 2)

A.I. Evaluation of the Solution

The candidate's solution correctly solves the problem. The candidate uses a recursive approach, which is the most efficient way to solve the Tower of Hanoi problem.

Evaluated at: 2022-11-13 06:16:10