首页 > 解决方案 > 递归函数计数。河内塔的台阶

问题描述

编写一个递归函数,返回解决 N 个盘的河内塔问题所需的步数。

输入 n=3 输出 7

这是代码-

private static int counttoh(int n,String T1,String T2,String T3)
 {int count=0;

     if(n==0)
     return 1; 


     count+=counttoh(n-1,T1,T3,T2);
     count+=counttoh(n-1,T3,T2,T1);

     return count;
 }

我的函数 counttoh 给出 4 作为输出,如果我正在做 return count-1 它给出 1 ,任何人都可以帮助我解决这个问题。

标签: recursiontowers-of-hanoi

解决方案


#include <stdio.h>

int move(int n, char source, char destination, char spare)
{ int count = 1;
if (n==1){
    printf("\n\nMove a disc from %c to %c", source, destination);
}
else{
    count += move(n-1, source, spare, destination);
             move(1, source, destination, spare);
    count += move(n-1, spare, destination, source);
}
return count;
}

int main()
{
int n, steps;
char A, B, C;
printf("Enter the number of disc :- ");
scanf("%d", &n);
printf("\nHere A is source, B is destination, C is spare.");
steps = move(n, 'A', 'B', 'C');
printf("\n\nNumber of steps taken is %d", steps);
return 0;
}

推荐阅读