Algo-Sim › Recursion & Backtracking

Tower of Hanoi

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Move n discs between three pegs: park n − 1 on the spare, move the biggest, then stack the n − 1 back. The peg roles swap at every level.

Problem

Three pegs A, B and C hold discs of sizes 1 to n; all start on A, largest at the bottom. Move them all to C. Each move takes the top disc of one peg and puts it on another, and a disc may never sit on a smaller one. Return the moves in order, each as "X->Y", using as few as possible.

Constraints

Edge cases to test

Follow-up questions

Why is 2ⁿ − 1 optimal?
The biggest disc must move at least once, and before that the other n − 1 discs must all reach the spare and later the target: at least 2 · T(n − 1) + 1 moves.
Can you do it without recursion?
Yes: alternate moving disc 1 one peg along a fixed cycle (direction set by n’s parity) with the only legal move that does not touch disc 1.
How much stack does it use?
O(n): the recursion depth is n even though the call tree has 2ⁿ − 1 calls.

Solution

Java

public List<String> towerOfHanoi(int n) {
    List<String> moves = new ArrayList<>();
    solve(n, 'A', 'C', 'B', moves);
    return moves;
}

private void solve(int n, char from, char to, char via, List<String> moves) {
    if (n == 1) {
        moves.add(from + "->" + to);
        return;
    }
    solve(n - 1, from, via, to, moves);
    moves.add(from + "->" + to);
    solve(n - 1, via, to, from, moves);
}

Python

def tower_of_hanoi(n):
    moves = []

    def solve(n, frm, to, via):
        if n == 1:
            moves.append(f"{frm}->{to}")
            return
        solve(n - 1, frm, via, to)
        moves.append(f"{frm}->{to}")
        solve(n - 1, via, to, frm)

    solve(n, "A", "C", "B")
    return moves

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<string> towerOfHanoi(int n) {
        vector<string> moves;
        solve(n, 'A', 'C', 'B', moves);
        return moves;
    }

  private:
    void solve(int n, char from, char to, char via, vector<string> &moves) {
        if (n == 1) {
            moves.push_back(string{from} + "->" + to);
            return;
        }
        solve(n - 1, from, via, to, moves);
        moves.push_back(string{from} + "->" + to);
        solve(n - 1, via, to, from, moves);
    }
};

More Recursion & Backtracking problems