Search code examples
algorithmtowers-of-hanoi

Hanoi Tower Algorithm using recursion, while show the step count


We all know the python code to solve Hanoi Tower problem looks like:

def hanoi(n, a, b, c):
    if n == 1:
        print a, '-->', c
        return
    hanoi(n-1, a, c, b)
    print a, '-->', c
    hanoi(n-1, b, a, c)

hanoi(4, 'A', 'B', 'C')

My question is where to add print('stepCount ={}'.format(stepCount)) to show the stepCount for each step.

****Update & Clarification***** while the output of the code above shows:

A > C
A > B
C > B
A > C
B > A
B > C
A > C

I am wondering if print statement can be added to the code to change the output to:

stepCount: 1
A > C
stepCount: 2
A > B
stepCount: 3
C > B
stepCount: 4
A > C
stepCount: 5
B > A
stepCount: 6
B > C
stepCount: 7
A > C

Solution

  • @emplatetypedef described a solution like the following:

    def hanoi(n, a, b, c, count):
        if n > 0:
            count = hanoi(n-1, a, c, b, count)
            count += 1
            print('stepCount: {}'.format(count))
            print('{} --> {}'.format(a, c))
            count = hanoi(n-1, b, a, c, count)
        return count
    
    hanoi(3, 'A', 'B', 'C', 0)
    

    It can also be implement with a global variable (yes I know ugh...):

    def hanoi(n, a, b, c):
        global stepCount
        if n > 0:
            hanoi(n-1, a, c, b)
            stepCount += 1
            print('stepCount: {}'.format(stepCount))
            print('{} --> {}'.format(a, c))
            hanoi(n-1, b, a, c)
    
    
    stepCount = 0
    hanoi(3, 'A', 'B', 'C')
    

    OUTPUT (of both code snippets)

    stepCount: 1
    A --> C
    stepCount: 2
    A --> B
    stepCount: 3
    C --> B
    stepCount: 4
    A --> C
    stepCount: 5
    B --> A
    stepCount: 6
    B --> C
    stepCount: 7
    A --> C