Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Python/Tower of Hanoi/Tower of Hanoi.md
Original file line number Diff line number Diff line change
@@ -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.
17 changes: 17 additions & 0 deletions Python/Tower of Hanoi/towerofhanoi.py
Original file line number Diff line number Diff line change
@@ -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