How to Solve the Tower of Hanoi Problem Using a Recursive Algorithm in Python?

Estimated read time 2 min read

The Tower of Hanoi problem is often solved using a recursive algorithm, which is a natural way to express the problem. Here is an example of how to solve the Tower of Hanoi problem using a recursive algorithm in Python:

def tower_of_hanoi(n, source, dest, temp):
    if n == 1:
        print("Move disk 1 from source", source, "to destination", dest)
        return
    tower_of_hanoi(n-1, source, temp, dest)
    print("Move disk", n, "from source", source, "to destination", dest)
    tower_of_hanoi(n-1, temp, dest, source)

Here, n represents the number of disks, source represents the starting peg, dest represents the destination peg, and temp represents the temporary buffer peg.

The base case of the recursion is when n is equal to 1. In this case, we simply move the top disk from the source peg to the dest peg and return.

If n is greater than 1, we first recursively move the top n-1 disks from the source peg to the temp peg, using the dest peg as a temporary buffer. Then, we move the n-th disk from the source peg to the dest peg. Finally, we recursively move the n-1 disks from the temp peg to the dest peg, using the source peg as a temporary buffer.

To use this function, simply call tower_of_hanoi(n, source, dest, temp) with the appropriate values for n, source, dest, and temp. The function will print out a sequence of moves that will solve the Tower of Hanoi problem for the given number of disks.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply