C++汉诺塔程序
- 提问者网友:呐年旧曙光
- 2021-06-03 04:23
- 五星知识达人网友:人间朝暮
- 2021-06-03 05:04
#include<iostream.h>
void Hanoi(int n,char a,char b,char c);
void Move(int num,char from,char to);
int main()
{
int n;
cout<<"Input the number of disk:";
cin>>n;
cout<<"The step of moving "<<n<<" disk:\n";
Hanoi(n,'A','B','C');
return 1;
}
void Hanoi(int n,char a,char b,char c )
{
if(n == 1)
{
Move(n,a,b);
}
else
{
Hanoi(n-1,a,c,b);
Move(n,a,b);
Hanoi(n-1,c,b,a);
}
}
void Move(int num,char from,char to)
{
cout<<"Move "<<num<<": from "<<from<<"to "<<to<<endl;
}
- 1楼网友:话散在刀尖上
- 2021-06-03 06:02
//C++汉诺塔
#include<iostream>
#include<iomanip>
using namespace std;
const int n=64;//盘子数目,注意:64个的时候我运行了5分钟都没有算完,定义小一些的数
void move(char,char);
void hannuota(int,char,char,char);
int main()
{
hannuota(n,'A','B','C');//ABC表示三座塔上的盘子
cout<<endl;
return 0;
}
void hannuota(int n,char a,char b,char c)//三座塔abc
{
if(n==1)move(a,c);
else{
hannuota(n-1,a,c,b);
move(a,c);
hannuota(n-1,b,a,c);//可以分析出搬运次数为2的N次方-1
}
};
void move(char a,char c)
{
cout<<a<<"-"<<c<<'\t';
}
#include<stdio.h>
#include<conio.h>
void move(char x,char y)
{
printf(" % c --> %c \n",x,y);
}
void hanoi(int n,char a,char b,char c)
{
if (n==1) move (a,c);
else
{
hanoi(n-1,a,c,b);
move (a,c);
hanoi(n-1,b,a,c);
}
}
int main (void)
{
int m;
printf ("input desk m:");
scanf("%d",&m);
hanoi (m,'a','b','c');
getch();
return 0;
}