#include<stdio.h>
#include <conio.h>
#include <easyx.h>
#include <stack>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
stack<int>M1;
stack<int>M2;
stack<int>M3;
queue<stack<int>>FIN;
void fanta(int n, char a, char b, char c);
void go(char a, char c);
void draw();
int main()
{
int n=0;
cout << "请输入梵塔层数" << endl;
cin >> n;
cout << "下面开始进行解答" << endl;
for (int i = 1; i <= n; i++)
{
M1.push(n-i+1);
}
FIN.push(M1);
FIN.push(M2);
FIN.push(M3);
fanta(n, 'A', 'B', 'C');
draw();
return 0;
}
void fanta(int n, char a, char b, char c)
{
if (n == 1)
{
cout << a << "->" << c << endl;
go(a, c);
FIN.push(M1);
FIN.push(M2);
FIN.push(M3);
stack<int>Mn=M1;
cout<<"A";
while(!Mn.empty()) {cout<<Mn.top(); Mn.pop();}
cout<<""<<endl;
Mn=M2;
cout<<"B";
while(!Mn.empty()) {cout<<Mn.top(); Mn.pop();}
cout<<""<<endl;
Mn=M3;
cout<<"C";
while(!Mn.empty()) {cout<<Mn.top(); Mn.pop();}
cout<<""<<endl;
}
else
{
fanta(n - 1, a, c, b);
cout << a << "->" << c << endl;
go(a, c);
FIN.push(M1);
FIN.push(M2);
FIN.push(M3);
stack<int>Mn=M1;
cout<<"A";
while(!Mn.empty()) {cout<<Mn.top(); Mn.pop();}
cout<<""<<endl;
Mn=M2;
cout<<"B";
while(!Mn.empty()) {cout<<Mn.top(); Mn.pop();}
cout<<""<<endl;
Mn=M3;
cout<<"C";
while(!Mn.empty()) {cout<<Mn.top(); Mn.pop();}
cout<<""<<endl;
fanta(n - 1, b, a, c);
}
}
void go(char a,char c)
{
if (a == 'A' && c == 'B')
{
M2.push(M1.top());
M1.pop();
}
else if (a == 'A' && c == 'C')
{
M3.push(M1.top());
M1.pop();
}
if (a == 'B' && c == 'A')
{
M1.push(M2.top());
M2.pop();
}
if (a == 'B' && c == 'C')
{
M3.push(M2.top());
M2.pop();
}
if (a == 'C' && c == 'A')
{
M1.push(M3.top());
M3.pop();
}
if (a == 'C' && c == 'B')
{
M2.push(M3.top());
M3.pop();
}
}
void draw()
{
int size = FIN.size();
initgraph(900, 600);
int den = 580;//基底
int width = 10;//每一层的高度
int jiange = 20;//层层之间的间隔
for (int i = 0; i < size; i += 3)
{
stack<int>M11(FIN.front());
FIN.pop();
stack<int>M22(FIN.front());
FIN.pop();
stack<int>M33(FIN.front());
FIN.pop();
int size1 = M11.size();
int size2 = M22.size();
int size3 = M33.size();
for (int i = 1; i <= size1; i++)
{
int length = M11.top();
M11.pop();
solidrectangle(150 - 5 * length, den - (size1 - i) * (width + jiange) - width,
150 + 5 * length, den - (size1 - i) * (width + jiange));
}
for (int i = 1; i <= size2; i++)
{
int length = M22.top();
M22.pop();
solidrectangle(450 - 5 * length, den - (size2 - i) * (width + jiange) - width,
450 + 5 * length, den - (size2 - i) * (width + jiange));
}
for (int i = 1; i <= size3; i++)
{
int length = M33.top();
M33.pop();
solidrectangle(750 - 5 * length, den - (size3 - i) * (width + jiange) - width,
750 + 5 * length, den - (size3 - i) * (width + jiange));
}
Sleep(200);
cleardevice();
}
}
zuoye1
最新推荐文章于 2024-07-16 21:06:27 发布