The Tower of Hanoi is a classic problem in computer science that involves moving a stack of disks of different sizes from one peg to another peg, with the constraint that a larger disk cannot be placed on top of a smaller disk.
To solve the Tower of Hanoi problem using recursive functions, you can follow these steps:
Define the recursive function hanoi (n, source, target, auxiliary) that takes four parameters:
n: the number of disks to move
source: the peg where the disks are initially stacked
target: the peg where the disks should be moved to
auxiliary: the spare peg that can be used to move disks around
def hanoi (n, source, target, auxiliary):
if n == 1:
print (f"Move disk 1 from {source} to {target}")
return
hanoi (n-1, source, auxiliary, target)
print (f"Move disk {n} from {source} to {target}")
hanoi (n-1, auxiliary, target, source)