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;
} 汉诺塔
最新推荐文章于 2016-08-11 00:16:19 发布
本文介绍了一种解决汉诺塔问题的方法,包括递归和非递归两种实现方式。通过具体的C++代码示例展示了如何移动不同数量的盘子,并详细解释了每一步的操作逻辑。
1138

被折叠的 条评论
为什么被折叠?



