Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
383 views

Hey everyone,

I've been working on the classic Tower of Hanoi problem, and I'm stuck on implementing the recursive solution. I have been referring to the article on the Algorithm for Tower of Hanoi, but I'm still having some trouble understanding how to code it correctly.

Here's the code I've attempted so far:

zpython
def tower_of_hanoi(n, source, destination, auxiliary):
    if n > 0:
        # Move n-1 disks from source to auxiliary
        tower_of_hanoi(n-1, source, auxiliary, destination)

        # Move the nth disk from source to destination
        print("Move disk", n, "from", source, "to", destination)

        # Move the n-1 disks from auxiliary to destination
        tower_of_hanoi(n-1, auxiliary, destination, source)

# Test the function
n = 3
tower_of_hanoi(n, 'A', 'C', 'B')
 

However, when I run this code, the output doesn't seem to be correct. The order of disk movements is not as expected. I'm not sure what I'm doing wrong here.

Could someone please help me understand what's going wrong with my code? Am I missing any crucial steps or making a logical mistake?

If possible, could someone provide a corrected version of the code that properly solves the Tower of Hanoi problem?

Thank you in advance for your assistance!

in Coding Resources by Expert (500 points) | 383 views

Please log in or register to answer this question.

Get best answers to any doubt/query/question related to programming , jobs, gate, internships and tech-companies. Feel free to ask a question and you will receive the best advice/suggestion related to anything you ask about software-engineering , development and programming problems .