利用栈解决汉诺塔问题
#include<iostream>
using namespace std
;
#include<stack>
#include<string>
class HanNuoTa{
stack
<int> m_n
;
stack
<string
>m_str
;
int n
;
string s
;
char ch
;
public:
void init(int n
, char ch1
= 'a', char ch2
= 'b', char ch3
= 'c'){
this->n
= n
;
s
= "abc";
s
[0] = ch1
;
s
[1] = ch2
;
s
[2] = ch3
;
this->m_n
.push(n
);
this->m_str
.push(s
);
}
void move(){
while(this->m_n
.size() != 0){
this->func1();
this->func2();
}
}
void func1(){
while(this->m_n
.top() > 1){
m_n
.push(m_n
.top() - 1);
s
= m_str
.top();
ch
= s
[1];
s
[1] = s
[2];
s
[2] = ch
;
m_str
.push(s
);
}
}
void func2(){
n
= this->m_n
.top();
this->m_n
.pop();
s
= this->m_str
.top();
this->m_str
.pop();
cout
<< s
[0] << "->" << s
[2] << endl
;
if(m_n
.size() != 0){
n
= this->m_n
.top();
this->m_n
.pop();
s
= this->m_str
.top();
this->m_str
.pop();
cout
<< s
[0] << "->" << s
[2] << endl
;
m_n
.push(n
-1);
ch
= s
[0];
s
[0] = s
[1];
s
[1] = ch
;
m_str
.push(s
);
}
}
};
int main(){
HanNuoTa han
;
int n
= 0;
cout
<< "请输入碟子个数n(将给出n个碟子从a借组b搬运到c的移动步骤):" << endl
;
cin
>> n
;
han
.init(n
);
han
.move();
return 0;
}
转载请注明原文地址: https://lol.8miu.com/read-16507.html