class term{
public:
term(int f, int tmp, int t, int n, int flag) :from(f),tmp(tmp) , to(t), n(n),flag(flag){}
int from;
int to;
int tmp;
int n;//表示从1...n的汉诺塔
int flag;//表示要输出的
};
void move(int from, int to, int n) {
cout<<"move "<<n<<" from "<<from<<" to "<<to<<endl;
}
void hanoi(int from, int tmp, int to, int n) {//
if (n >0) {
hanoi(from,to, tmp , n-1);
move(from,to,n);
hanoi(tmp,from, to, n-1);
}
}
void nonRecurHanoi(int from, int tmp, int to, int n) {
stack<term> st;
st.push(term(from, tmp, to,n,n==1?1:0));
while(!st.empty()) {
term t = st.top();
st.pop();
if (t.flag) {
move(t.from,t.to,t.n);
}
else {
int flag = 0;
if (t.n - 1 ==1)
flag = 1;
st.push(term(t.tmp,t.from,t.to,t.n - 1, flag));//这里的顺序和递归调用的顺序正好相反
st.push(term(t.from,t.tmp,t.to,t.n,1));
st.push(term(t.from, t.to, t.tmp, t.n -1 , flag));
}
}
}
int main()
{
hanoi(0,1,2,4);
cout<<endl;
nonRecurHanoi(0,1,2,4);
return 0;
}
汉诺塔
最新推荐文章于 2013-03-27 16:43:01 发布