tool · interactive solver · classic algorithm · recursion visualized

Tower of Hanoi

Interactive Tower of Hanoi visualizer. Pick the number N of disks, press play and watch the recursive algorithm move them one at a time. Every operation is logged below. The optimal solution takes 2^n − 1 moves.

moves(n) = 2n − 1

hanoi::solver — floriano@neural-link idle
move 00 / 15
progress
last op
tail -f /hanoi/operations.log 0 ops

    The algorithm, in three lines

    The classic Tower of Hanoi solution is recursive: to move n disks from A to C using B as a buffer, first move the n−1 subset onto B, then the largest disk onto C, then the subset from B to C.

    function hanoi(n, from, via, to):
        if n == 0: return
        hanoi(n - 1, from, to, via)   // 1. move top n-1 disks from FROM to VIA
        move disk n: from → to        // 2. move the largest free disk to TO
        hanoi(n - 1, via, from, to)   // 3. move n-1 disks from VIA to TO
    

    The minimum number of moves grows exponentially. n = 10 needs 1023 operations. n = 20 needs more than a million.