The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+12 votes
817 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 (59.5k points)
recategorized by | 817 views
+1
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

+16 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 Boss (15.3k points)
edited by
+7

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) ?

+2
correct now?
+1
yes
+1
Yes it is correct !!
+2
+4 votes
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 Boss (14.3k points)


Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

39,713 questions
46,750 answers
140,552 comments
58,385 users