diff --git a/Python/Tower of Hanoi/Tower of Hanoi.md b/Python/Tower of Hanoi/Tower of Hanoi.md new file mode 100644 index 0000000..a13f4b2 --- /dev/null +++ b/Python/Tower of Hanoi/Tower of Hanoi.md @@ -0,0 +1,12 @@ +# Tower of Hanoi + +This is a very popular puzzle. There are 3 rods A, B, C. The goal is to move the stack of disks from A to C while following the rules below: + +- Only one disk can be moved at a time and it has to be the upper disk in the stack. +- Bigger disk should not be placed on top of smaller disc. + +For a N disks, to move from A to C, + +1. Shift N-1 disks to B using C as a temporary rod. +2. Shift the last disk to C. +3. Now use A as a temporary rod and shift all the disks from B to C. diff --git a/Python/Tower of Hanoi/towerofhanoi.py b/Python/Tower of Hanoi/towerofhanoi.py new file mode 100644 index 0000000..4ad4753 --- /dev/null +++ b/Python/Tower of Hanoi/towerofhanoi.py @@ -0,0 +1,17 @@ +# Recursive logic to solve tower of hanoi problem +def tower_of_hanoi(number, source, temporary, destination): + if number == 1: + print("Move disk 1 from", source, "to", destination) + return + tower_of_hanoi(n-1, source, temporary, destination) + print("Move disk", n, "from", source, "to", destination) + tower_of_hanoi(n-1, temporary, destination, source) + +# 1. Shift N-1 disks to B using C as a temporary rod. +# 2. Shift the last disk to C. +# 3. Now use A as a temporary rod and shift all the disks from B to C. + +n = int(input("Enter the number of disks")) +tower_of_hanoi(n, 'A', 'B', 'C') +# A is the source, C is the destination +