Back to Solutions

Tower Of Hanoi

Explanation

A kid's game huh. Harder than you think. Here, we are required to move the left stack to the right stack and use the middle stack as the helper stack.

We can do this recursively by moving the top n - 1 disks from the left stack to the middle stack, then moving the bottom disk to the right stack, then moving the n - 1 disks from the middle stack to the right stack.

Code

def move(start: int, helper: int, end: int, disks: int):
    if disks == 1:
        print(start, end)
    else:
        move(start, end, helper, disks - 1)
        move(start, helper, end, 1)
        move(helper, start, end, disks - 1)

n = int(input())
print(2 ** n - 1)
move(1, 2, 3, n)