Menu

Artificial Intelligence Using Python [ Lab Programs ]


Write a Program to Implement Tower of Hanoi using Python.

SOURCE CODE :

 def tower_of_hanoi(num, source, aux, target):
    """
	num (int): Number of disks.
    source (str): The name of the source tower.
    aux (str): The name of the auxiliary tower.
    target (str): The name of the target tower.
    """
    if num == 1:
        print(f"Move disk 1 from {source} to {target}")
        return
    # Move num-1 disks from source to auxiliary
    tower_of_hanoi(num - 1, source, target, aux)
    print(f"Move disk {num} from {source} to {target}")
    # Move the num-1 disks from auxiliary to target
    tower_of_hanoi(num - 1, aux, source, target)

# Example usage
num_disks = 3
tower_of_hanoi(num_disks, "A", "B", "C")


OUTPUT :


Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Related Content :

Artificial Intelligence Using Python

   Write a Program to Implement the following using Python

1) Breadth First Search View Solution

2) Depth First Search View Solution

3) Tic-Tac-Toe game View Solution

4) 8-Puzzle problem View Solution

5) Water-Jug problem View Solution

6) Travelling Salesman Problem View Solution

7) Tower of Hanoi View Solution

8) Monkey Banana Problem View Solution

9) Alpha-Beta Pruning View Solution

10) 8-Queens Problem View Solution