|
| 1 | +''' |
| 2 | + Tower of Hanoi |
| 3 | +Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: |
| 4 | +1) Only one disk can be moved at a time. |
| 5 | +2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. |
| 6 | +3) No disk may be placed on top of a smaller disk. |
| 7 | +
|
| 8 | +ALGO- |
| 9 | +
|
| 10 | +1-Create a tower_of_hanoi recursive function and pass two arguments: the number of disks n and the name of the rods such as source, aux, and target. |
| 11 | +2-We can define the base case when the number of disks is 1. In this case, simply move the one disk from the source to target and return. |
| 12 | +3-Now, move remaining n-1 disks from source to auxiliary using the target as the auxiliary. |
| 13 | +4-Then, the remaining 1 disk move on the source to target. |
| 14 | +5-Move the n-1 disks on the auxiliary to the target using the source as the auxiliary. |
| 15 | +
|
| 16 | +''' |
| 17 | + |
| 18 | + |
| 19 | +def tower_of_hanoi(n, source, auxiliary, target): |
| 20 | + if n == 1: |
| 21 | + print("Move disk 1 from source", source, "to destination", target) |
| 22 | + return |
| 23 | + tower_of_hanoi(n-1, source, target, auxiliary) |
| 24 | + print("Move disk", n, "from source", source, "to destination", target) |
| 25 | + tower_of_hanoi(n-1, auxiliary, source, target) |
| 26 | + |
| 27 | + |
| 28 | +print(tower_of_hanoi(4, 'A', 'B', 'C')) |
| 29 | +# Move disk 1 from source A to destination B |
| 30 | +# Move disk 2 from source A to destination C |
| 31 | +# Move disk 1 from source B to destination C |
| 32 | +# Move disk 3 from source A to destination B |
| 33 | +# Move disk 1 from source C to destination A |
| 34 | +# Move disk 2 from source C to destination B |
| 35 | +# Move disk 1 from source A to destination B |
| 36 | +# Move disk 4 from source A to destination C |
| 37 | +# Move disk 1 from source B to destination C |
| 38 | +# Move disk 2 from source B to destination A |
| 39 | +# Move disk 1 from source C to destination A |
| 40 | +# Move disk 3 from source B to destination C |
| 41 | +# Move disk 1 from source A to destination B |
| 42 | +# Move disk 2 from source A to destination C |
| 43 | +# Move disk 1 from source B to destination C |
0 commit comments