← All examples

Towers of Hanoi

Python Recursion

classic recursion

Flowchart (ISO 5807)

YesNoStartInput n, src, dst, auxn == 1Output src «->» dstReturnEndhanoi(n - 1, src, aux, dst)Output src «->» dsthanoi(n - 1, aux, dst, src)EndFigure 1 — hanoi

Source code

def hanoi(n, src, dst, aux):
    if n == 1:
        print(src, "->", dst)
        return
    hanoi(n - 1, src, aux, dst)
    print(src, "->", dst)
    hanoi(n - 1, aux, dst, src)