|
| 1 | +"""Tower of Hanoi is a mathematical puzzle where we have three rods |
| 2 | +(A, B, and C) and N disks. Initially, all the disks are stacked in decreasing |
| 3 | +value of diameter i.e., the smallest disk is placed on the top and they are on |
| 4 | +rod A. The objective of the puzzle is to move the entire stack to another rod |
| 5 | +(here considered C), obeying the following simple rules: |
| 6 | + - Only one disk can be moved at a time. |
| 7 | + - Each move consists of taking the upper disk from one of the stacks and |
| 8 | + placing it on top of another stack i.e. a disk can only be moved if it |
| 9 | + is the uppermost disk on a stack. |
| 10 | + - No disk may be placed on top of a smaller disk.""" |
| 11 | + |
| 12 | + |
| 13 | +def TowerOfHanoi(n, from_rod, to_rod, aux_rod, y): |
| 14 | + if n == 0: |
| 15 | + return y |
| 16 | + y = TowerOfHanoi(n - 1, from_rod, aux_rod, to_rod, y) |
| 17 | + print("Move disk", n, "from rod", from_rod, "to rod", to_rod) |
| 18 | + y += 1 |
| 19 | + y = TowerOfHanoi(n - 1, aux_rod, to_rod, from_rod, y) |
| 20 | + return y |
| 21 | + |
| 22 | + |
| 23 | +if __name__ == "__main__": |
| 24 | + temp = TowerOfHanoi(int(input("No. of disks: ")), "A", "C", "B", 0) |
| 25 | + print(f"{temp} moves") |
0 commit comments