Search code examples
algorithmtowers-of-hanoi

recursive solution for tower of hanoi


I am reading algorithms in C++ book by RobetSedwick. Here author is explaning about Towers of Hanoi using divide and conquer design and recurrence.

Followin code is recursion solution to the proble. It specifies which disk should be shifted at each step, and in which direction (+ means move one peg to the right, cycling to the leftmost peg when on the right most peg; and - means move one peg to the left, cycling to the right most peg when on the left most peg).

Disk3          
Disk2
Disk1

Peg1      Peg2   Peg3

My question what does author mean above "cycling to the leftmost peg" when disk is on left peg (ie., Peg 1) how do we cyclic to left most peg?

Author also mentioned that Recursion is based on following idea: To move N disks one peg to the right, we first move top N-1 disk one peg to the left, then shift disk N one peg to the right, then move N-1 disks one more peg to the left (on to disk N).

I am confused with left and right terminology above. Can any one please explain.

void hanoi(int N, int d)
  {
    if (N == 0) return;
    hanoi(N-1, -d);
    shift(N, d);    
    hanoi(N-1, -d);
  } 

Solution

  • It just means:

    Cycling to the right:

    peg1 -> peg2
    peg2 -> peg3
    peg3 -> peg1
    

    Cycling to the left

    peg1 -> peg3
    peg2 -> peg1
    peg3 -> peg2