GATE CSE
First time here? Checkout the FAQ!
x
+4 votes
475 views

The following recursive function in C is a solution to the Towers of Hanoi problem.

void move(int n, char A, char B, char C)  {
    if (......................) {
        move (.............................);
        printf("Move disk %d from pole %c to pole %c\n", n, A,C);
        move (.....................);
    }
}

Fill in the dotted parts of the solution.

asked in Programming by Veteran (64.6k points)  
recategorized by | 475 views
If(n==1) { Printf("\n %s %c %s %c","move disk1 from pole",A,"to pole",B); Return; } Towers(n-1,A,C,B); Printf.... Towers(n-1,C,B,A);

2 Answers

+11 votes
Best answer
void move(int n, char A, char B, char C) {
    if (n > 0) {
        move (n-1, A, C, B);
        printf("Move disk %d from pole %c to pole %c\n", n, A, C);
        move (n-1, B, A, C);
    } 
}

 

answered by Veteran (13.2k points)  
edited by

The snippet tells that A must be a source and C the destination.That means function would be move(src,spare,dest).

Firstcall(A,B,C) A to C using B intermediate

If we go by this defination, first move(n-1,A,C,B) will move n-1 disks to B using C as spare.

Now the 1 that remains is moved from A(src) to C(dest).

Shouldn't the last call then be move(n-1,B,A,C) ,that is moving the n-1 disk that were previously moved to intermediate node B over C(the destination) ?

correct now?
yes
Yes it is correct !!
+1 vote
If(n==1) { Printf("\n %s %c %s %c","move disk1 from pole",A,"to pole",B); Return; } Towers(n-1,A,C,B); Printf.... Towers(n-1,C,B,A);
answered by Veteran (13.3k points)  


Top Users Sep 2017
  1. Habibkhan

    6836 Points

  2. Arjun

    2310 Points

  3. Warrior

    2306 Points

  4. rishu_darkshadow

    2092 Points

  5. A_i_$_h

    2004 Points

  6. nikunj

    1980 Points

  7. manu00x

    1750 Points

  8. Bikram

    1744 Points

  9. SiddharthMahapatra

    1718 Points

  10. makhdoom ghaya

    1690 Points


26,038 questions
33,651 answers
79,695 comments
31,069 users