Recursion - Tower of Hanoi

 # Recursion

# Tower of Hanoi 


def TowerOfHanoi(n , src, dest, aux):

    if n == 0:

        return

    TowerOfHanoi(n-1, src, aux, dest)

    print("Move disk",n,"from rod",src,"to rod",dest)

    TowerOfHanoi(n-1, aux, dest, src)

         

# Driver code

n = 3

TowerOfHanoi(n, 'A', 'C', 'B')


"""

Sample output

>python TowerofHanoi.py

Move disk 1 from rod A to rod C

Move disk 2 from rod A to rod B

Move disk 1 from rod C to rod B

Move disk 3 from rod A to rod C

Move disk 1 from rod B to rod A

Move disk 2 from rod B to rod C

Move disk 1 from rod A to rod C

"""

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu