汉诺塔

bingwangziderensheng 2009-05-12 04:19:24
#include <stdio.h>

void move(int n,char x,char y,char z)
{
if(n==1)
printf("%c-->%c\n",x,z);
else
{
//把上面的n-1个圆盘先从x搬到y,然后才能把第n个从x搬到z
move(n-1,x,z,y);

printf("%c-->%c\n",x,z);//表示一个圆盘从x移动到z

//然后把n-1个圆盘先从y搬到z
move(n-1,y,x,z);
}
}

main()
{
int h;
printf("\ninput number:\n");
scanf("%d",&h);
printf("the step to moving %2d diskes:\n",h);
move(h,'a','b','c');
}

如何把例中的move()函数修改为用循环语句来实现(即递归改嵌套)?
...全文
104 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
weekice88 2009-05-14
  • 打赏
  • 举报
回复
每次看到这个就头大。。。
up
碎方脸 2009-05-14
  • 打赏
  • 举报
回复
这是copy一楼给出的答案,但是能不能解释下啊

#include <iostream>
using namespace std;

//圆盘的个数最多为64
const int MAX = 64;

//用来表示每根柱子的信息
struct st
{
int s[MAX]; //柱子上的圆盘存储情况
int top; //栈顶,用来最上面的圆盘
char name; //柱子的名字,可以是A,B,C中的一个
int Top()//取栈顶元素
{
return(s[top]);
}
int Pop()//出栈
{
return(s[top--]);
}
void Push(int x)//入栈
{
s[++top] = x;
}
} ;

long Pow(int x, int y); //计算x^y
void Creat(st ta[], int n); //给结构数组设置初值
void Hannuota(st ta[], long max); //移动汉诺塔的主要函数

int main(void)
{
int n;
cin >> n; //输入圆盘的个数
st ta[3]; //三根柱子的信息用结构数组存储
Creat(ta, n); //给结构数组设置初值

long max = Pow(2, n) - 1;//动的次数应等于2^n - 1
Hannuota(ta, max);//移动汉诺塔的主要函数

system(“pause”);
return(0);
}

void Creat(st ta[], int n)
{
ta[0].name = ‘A’;
ta[0].top = n-1;
//把所有的圆盘按从大到小的顺序放在柱子A上
for(int i=0; i<n; i++)
ta[0].s[i] = n - i;
//柱子B,C上开始没有没有圆盘
ta[1].top = ta[2].top = 0;
for(int i=0; i<n; i++)
ta[1].s[i] = ta[2].s[i] = 0;
//若n为偶数,按顺时针方向依次摆放 A B C
if(n%2 == 0)
{
ta[1].name = ‘B’;
ta[2].name = ‘C’;
}
else //若n为奇数,按顺时针方向依次摆放 A C B
{
ta[1].name = ‘C’;
ta[2].name = ‘B’;
}
}

long Pow(int x, int y)
{
long sum = 1;
for(int i=0; i<y; i++)
sum *= x;

return(sum);
}

void Hannuota(st ta[], long max)
{
int k = 0; //累计移动的次数
int i = 0;
int ch;
while(k < max)
{
//按顺时针方向把圆盘1从现在的柱子移动到下一根柱子
ch = ta[i%3].Pop();
ta[(i+1)%3].Push(ch);
cout << ++k << “: “ <<
“Move disk “ << ch << ” from “ << ta[i%3].name <<
” to “ << ta[(i+1)%3].name << endl;
i++;
//把另外两根柱子上可以移动的圆盘移动到新的柱子上
if(k < max)
{ //把非空柱子上的圆盘移动到空柱子上,当两根柱子都为空时,移动较小的圆盘
if(ta[(i+1)%3].Top() == 0 ||
ta[(i-1)%3].Top() > 0 &&
ta[(i+1)%3].Top() > ta[(i-1)%3].Top())
{
ch = ta[(i-1)%3].Pop();
ta[(i+1)%3].Push(ch);
cout << ++k << “: “ << “Move disk “
<< ch << ” from “ << ta[(i-1)%3].name
<< ” to “ << ta[(i+1)%3].name << endl;
}
else
{
ch = ta[(i+1)%3].Pop();
ta[(i-1)%3].Push(ch);
cout << ++k << “: “ << “Move disk “
<< ch << ” from “ << ta[(i+1)%3].name
<< ” to “ << ta[(i-1)%3].name << endl;
}
}
}
}




  • 打赏
  • 举报
回复
C++不懂
lpf000 2009-05-12
  • 打赏
  • 举报
回复
怎么嵌套,多少套。
liliangbao 2009-05-12
  • 打赏
  • 举报
回复
帮顶~
lingyin55 2009-05-12
  • 打赏
  • 举报
回复
参考下

汉诺塔算法的递归与非递归的C以及C++源代码

http://blog.csdn.net/y4c1/archive/2008/08/22/2815250.aspx

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧