/*
Towers of Hanoi Problem
*/
#include<iostream>
using namespace std;
#define size 100
struct Stack
{
int m[size]; //Flag; move the plan's time
int n[size]; //the number of plans
char a[size];
char b[size];
char c[size];
int top;
};
void Pop(int &m,int &n,char &a,char &b,char &c,Stack &s)
{
if( s.top == 0 )
cout<<"Stack is Empty."<<endl;
else
{
m = s.m[s.top];
n = s.n[s.top];
a = s.a[s.top];
b = s.b[s.top];
c = s.c[s.top];
s.top--;
}
}
void Push(int m,int n,char a,char b,char c,Stack &s)
{
if( s.top > size )
cout<<"Stack is Full."<<endl;
else
{
s.top++;
s.m[s.top] = m;
s.n[s.top] = n;
s.a[s.top] = a;
s.b[s.top] = b;
s.c[s.top] = c;
}
}
void Hanoi(int m,int n,char a,char b,char c, Stack s)
{
Push(m,n,a,b,c,s);
while( s.top > 0 )
{
Pop(m,n,a,b,c,s);
if( m <= 1 )
{
if( n == 0 )
continue;
else
cout<<"第 "<<n<<" 號盤子: 從第 "<<a<<" 根柱子 ---> 第 "<<c<<" 根柱子"<<endl<<endl;
}
else
{
Push(n-1,n-1,b,a,c,s); // b to c
Push(1,n,a,b,c,s); // a to c
Push(n-1,n-1,a,c,b,s); // a to b 原本應該此項為第一項 但Stack先進後出所以變最後一項
}
}
}
int main()
{
char a = 'A',b = 'B',c = 'C';
int n;
Stack s;
s.top = 0;
cout<<"請輸入盤子數目: ";
cin>>n;
cout<<endl;
Hanoi(3,n,a,b,c,s);
return 0;
}
執行結果: