首页 > 其他 > 详细

用栈来递归 模板 honoi

时间:2018-04-03 14:09:28      阅读:199      评论:0      收藏:0      [点我收藏+]

用栈来模拟递归的技巧

 

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<cstring>
#include<set>
#include<algorithm>
#include<stack>
#include<string>
#include<cstdio>
#define _for(i, a, b) for (int i = (a); i<(b); ++i)
using namespace std;
struct problem {
    int n;
    char scr, mid, dest;
    problem(int nn, char s, char m, char d) :n(nn), scr(s), mid(m), dest(d) {}
};
stack<problem> stk;

int main()                                  
{
    int n;
    cin >> n;
    stk.push(problem(n, A, B, C));
        while (!stk.empty()) {
            problem now = stk.top();
            stk.pop();
            if (now.n == 1) { cout << now.scr << "->" << now.dest << endl; }
            else {
                stk.push(problem(now.n - 1, now.mid, now.scr, now.dest));//先放最后一个子问题
                stk.push(problem(1, now.scr, now.mid, now.dest));
                stk.push(problem(now.n - 1, now.scr, now.dest, now.mid));
            }
        }
    
    system("pause");
} 

 

用栈来递归 模板 honoi

原文:https://www.cnblogs.com/SuuT/p/8707779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!