Towers of Hanoi

8.6 Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (Le., each disk sits on top of an even larger one). You have the following constraints:

(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.

We can solve Towers of Hanoi by solving the smaller associated sub problems. For example, if we have 4 disks and 3 rods [A, B, and C], then we can reduce that problem by:

  1. Move the top n-1 disks from A to B

  2. Move the nth disk from A to C.

  3. Move the n-1 disks from B to C.

Even though moving 3 disks at a time is an illegal move, this process is repeated (recurred on) until there is 1 disk, in which case the top disk will move from A to C. The same goes for the third step.

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
    if (n == 1)
        printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
    towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
    printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
    towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);

int main()
    int n_disks = 4; 
    // move disks from rod A to C by buffer rod B
    towerOfHanoi(n_disks, 'A', 'C', 'B');  // A, B and C are names of rods

Last updated