TheAlgorithms-C-Plus-Plus/others/Tower of Hanoi.cpp

74 lines
914 B
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-12-24 01:30:49 +08:00
using namespace std;
struct tower
{
int values[10];
int top;
2019-08-21 10:10:08 +08:00
} F, U, T;
2017-12-24 01:30:49 +08:00
void show()
{
2019-08-21 10:10:08 +08:00
cout << "\n\n\tF : ";
for (int i = 0; i < F.top; i++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << F.values[i] << "\t";
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
cout << "\n\tU : ";
for (int i = 0; i < U.top; i++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << U.values[i] << "\t";
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
cout << "\n\tT : ";
for (int i = 0; i < T.top; i++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << T.values[i] << "\t";
2017-12-24 01:30:49 +08:00
}
}
void mov(tower &From, tower &To)
{
--From.top;
2019-08-21 10:10:08 +08:00
To.values[To.top] = From.values[From.top];
2017-12-24 01:30:49 +08:00
++To.top;
}
void TH(int n, tower &From, tower &Using, tower &To)
{
2019-08-21 10:10:08 +08:00
if (n == 1)
2017-12-24 01:30:49 +08:00
{
mov(From, To);
show();
}
else
{
2019-08-21 10:10:08 +08:00
TH(n - 1, From, To, Using);
2017-12-24 01:30:49 +08:00
mov(From, To);
show();
2019-08-21 10:10:08 +08:00
TH(n - 1, Using, From, To);
2017-12-24 01:30:49 +08:00
}
}
int main()
{
2019-08-21 10:10:08 +08:00
F.top = 0;
U.top = 0;
T.top = 0;
2017-12-24 01:30:49 +08:00
int no;
2019-08-21 10:10:08 +08:00
cout << "\nEnter number of discs : ";
2017-12-24 01:30:49 +08:00
cin >> no;
2019-08-21 10:10:08 +08:00
for (int i = no; i > 0; i--)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
F.values[F.top++] = i;
2017-12-24 01:30:49 +08:00
};
show();
TH(no, F, U, T);
return 0;
}