用C或C++实现下面一个汉诺塔问题:

2025-04-23 13:02:44
推荐回答(2个)
回答1:

hannuota(int n,char A,chae B,char C) //n是有多少个盘子,A,B,C是三个拖盘,A是起始盘子,C是最后移动结束后的盘子,B是中间过渡的。
{
if(n==1) move(A,C);//move是一个后的显示函数“cout<//如果一个盘子,显然直接从A移到C即可,move(A,C)的意思就是从A盘移到C盘,A,C是两个参数
else //如果不是一个盘子的移动方法
{
hannuota(n-1,A,C,B);// 这个是将上面的n-1个盘子从A,通过C,移动到B;这样,就省下1个盘子了,你就可以直接从A移动到C了。
计算机是怎么执行的这个语句?什么顺序呢?
move(A,C); //这个就是将最后一个盘子,从A移动到C,像我上面说的。
hannuota(n-1,B,A,C);//刚才的n-1个盘子从A,通过C,移动到B,还记得吧,这回将这n-1个盘子,从B,通过A,移动到C上面,就完成了,因为你最下面的一个盘子你已经移过去了。如果当n>1的时候,始终递归调用hannuota这个函数,直到最后n==1这样的话,就可以通过上面的n==1操作来完成了。就是递归的终点了。
}
}

回答2:

#include
int main()
{
void hanoi(int n,char one,char two,char three); // 对hanoi函数的声明
int m;
printf("input the number of diskes:");
scanf("%d",&m);
printf("The step to move %d diskes:\n",m);
hanoi(m,'A','B','C');
}

void hanoi(int n,char one,char two,char three) // 定义hanoi函数
// 将n个盘从one座借助two座,移到three座
{
void move(char x,char y); // 对move函数的声明
if(n==1)
move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}

void move(char x,char y) // 定义move函数
{
printf("%c-->%c\n",x,y);
}