在书上看到的: “汉诺塔问题”:
在寺庙的一根柱子上,从上到下,依次从小到大叠放着N个碟子,现在要将这些碟子移动到另外一根柱子上面去,但是一次只能移动一个碟子,且碟子不能把大的叠放在小的上面。除了原来叠放碟子的柱子A,要移碟子过去的目标柱子B,还有一个可以作中转的柱子C,求移动次序?
书上讲解了一点,说是用 递归,但我不明白具体的操作,逻辑关系?
希望各位高手能帮忙讲解一下,不胜感激!
#include <stdio.h>
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
void hanoi(int n,char one,char two,char three)
{
if(n==1) move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
main()
{
int m;
printf("input the unmber of diskes:");
scanf("%d",&m);
printf("the step to moving %3d diskes:\n",m);
hanoi(m,'A','B','C');
}
#include <stdio.h>
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
void hanoi(int n,char one,char two,char three)
{
if(n==1) move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
main()
{
int m;
printf("input the unmber of diskes:");
scanf("%d",&m);
printf("the step to moving %3d diskes:\n",m);
hanoi(m,'A','B','C');
}
Thank you so much!
我把它改成C++的了:
#include <iostream>
using namespace std;
void move(char x,char y)
{
cout<<x<<"-->"<<y<<endl;
}
void hanoi(int n,char one,char two,char three)
{
if(n==1) move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
int main()
{
int N;
cout<<"input the unmber of diskes:"<<endl;
cin>>N;
cout<<"the step to moving "<<N<<" diskes:"<<endl;
hanoi(N,'A','B','C');
return 0;
}