We solve the Tower of Hanoi by breaking it into three sub-problems:
- Move
n-1disks from source to auxiliary. - Move the largest disk from source to target.
- Move
n-1disks from auxiliary to target.
- Base case: If
n == 1, move disk 1 from source to target directly. - Recursively move
n-1disks from source to auxiliary using target as helper. - Print: Move disk
nfrom source to target. - Recursively move
n-1disks from auxiliary to target using source as helper.
- Time Complexity: O(2^N - 1) moves.
- Space Complexity: O(N) (recursion stack).
def tower_of_hanoi(n, source='A', target='C', auxiliary='B'):
if n == 1:
print(f"Move disk 1 from Rod {source} to Rod {target}")
return
tower_of_hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from Rod {source} to Rod {target}")
tower_of_hanoi(n - 1, auxiliary, target, source)