|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <stdio.h>
- void hanoi_tower(int n,int ox, int tx, int mx)
- {
- if(n<1){
- printf("Error: n>=1\n");
- }else if (n==1){
- printf("%d->%d\n",ox,tx);
- }else{
- hanio_tower(n-1,ox,tx,mx);
- printf("%d->%d\n",ox,tx);
- hanoi_tower(n-1,tx,ox,mx);
- }
- }
- int main(void)
- {
- int n;
- printf("Enter the height of the tower");
- scanf("%d",&n);
- hanio_tower(n,1,3,2);
- return 0;
- }
复制代码
请问哪里有问题?
你要弄明白hanoi分三步,后面这三个参数的位置移动不要弄错了
从ox经过mx移动到tx,分三步:
第一步,把前n-1个从ox经过tx移动到mx;
第二步,把最下面的一个从ox移动到tx;
第三步,把n-1个从mx经过ox移动到tx
- #include <stdio.h>
- void hanoi_tower(int n,int ox, int tx, int mx)
- {
- if(n<1){
- printf("Error: n>=1\n");
- }else if (n==1){
- printf("%d->%d\n",ox,tx);
- }else{
- hanoi_tower(n-1,ox,mx,tx);//拼写错误,hanoi_tower写成了hanio_tower;后面的参数位置也写错了,mx和tx写反了
- printf("%d->%d\n",ox,tx);
- hanoi_tower(n-1,mx,tx,ox);//后面的参数位置也写错了
- }
- }
- int main(void)
- {
- int n;
- printf("Enter the height of the tower");
- scanf("%d",&n);
- hanoi_tower(n,1,3,2);//拼写错误,hanoi_tower写成了hanio_tower
- return 0;
- }
复制代码
|
|