Day 1: Hanoi tower

Tomáš Bouda
100 days of algorithms
1 min readMar 25, 2017

Let’s begin with a simple algorithm, yet, mind-bending if you have never seen it before. Hanoi tower has a beautiful literate solution using recursion.

Just think of it, we need to move the largest disk to right tower, first. For that, we need to move all but this disk to middle tower. Hence we are solving the very same problem [twice] with one less disk.

To move N disks from left to right:
#1 [recursively] move N-1 disks from left to middle
#2 move largest disk from left to right
#3 [recursively] move N-1 disks from middle to right

algorithm

https://github.com/coells/100days

def hanoi(height, left='left', right='right', middle='middle'):
if height:
hanoi(height - 1, left, middle, right)
print(left, '=>', right)
hanoi(height - 1, middle, right, left)

test

> hanoi(3)left => right
left => middle
right => middle
left => right
middle => left
middle => right
left => right

--

--