Skip to content

Towers of Hanoi

Python 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

Python
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)

The editor opens with this code — change it and the chart redraws.

Language
Python
Constructs
classic recursion
Topic
Recursion
Formats
Word, Visio, draw.io, PDF, SVG

Related examples