汉诺塔问题的递归求解
来源:互联网 发布:log4net Oracle数据库 编辑:程序博客网 时间:2024/05/23 05:06
/**
* Tower of Hanoi is a typical problem about dynamic programming. It resolve a big problem to a serices of smaller problem continuously, untill we get a set of basic operation.
*/
#include <stdio.h>#include <iostream>/** there are three pegs.*/enum PEGTYPE { PT_A, PT_B, PT_C,};class HanoiT { public: /* * core function */ bool solve( PEGTYPE from, PEGTYPE to, int quant); private: /* * a basic move operation. */ bool basic_op( PEGTYPE from, PEGTYPE to, int num); bool get_rest_one( PEGTYPE one, PEGTYPE two, PEGTYPE &rest); /* * the number of disk. */ int quant;};/*** core function for solve this problem. It will call itself recursively* to resolve the problem.*/bool HanoiT::solve( PEGTYPE from, PEGTYPE to, int quant){ if( quant==1) { /* * To the end of this resolve operation. */ this->basic_op( from, to, quant); } else { /* * Here is the core to solve this problem. Every complicated problem will * be resolve into three simpler parts. */ PEGTYPErest; this->get_rest_one( from, to, rest); this->solve( from, rest, quant -1); this->basic_op( from, to, quant); this->solve( rest, to, quant -1); } return true;}/*** there are three independent pegs. This function will get the rest one when* we enter two of them. return value will be store in @rest.*/bool HanoiT::get_rest_one(PEGTYPE one,PEGTYPE two, PEGTYPE &rest){/** Here, use a trick to compute the result.*/ switch( one + two) { case PT_A+PT_B: rest = PT_C; break; case PT_A+PT_C: rest = PT_B; break; case PT_B+PT_C: rest = PT_A; break; default : break; } return true;}/*** a basic operation. it should have contained a operation about move a disk.* but , obviously, we could do a trick on it.*/bool HanoiT::basic_op(PEGTYPE from,PEGTYPE to,int num){ static intcount = 0; printf("[%4d] %d-->%d \n", count, from, to); count ++; return true;}int main( ){ HanoiThan; han.solve( PT_A, PT_C, 4); return 0;}
0 0
- 汉诺塔问题的递归求解
- 汉诺塔问题的递归求解
- 递归求解汉诺塔问题
- 汉诺塔问题递归求解
- 汉诺塔问题的递归求解方法
- 迷宫问题的递归求解
- 汉诺塔问题递归算法求解
- Java递归求解汉诺塔问题
- 汉诺塔问题(递归求解)
- 递归法求解 汉诺塔问题
- 黑马程序员--汉诺塔问题的递归求解C语言
- 汉诺塔的递归求解分析
- 递归程序求解问题的通用法则
- 简单的递归求解乘方问题
- 八皇后问题的递归求解
- 递归求解整数的分划问题
- 从“递归结构”到解汉诺塔问题的求解
- 用递归方法求解汉诺塔问题
- 二叉树的镜像 (面试题 19)
- c++编译九九乘法表
- 打卡13-perl function-reverse/chop
- hibernate的hibernate.jdbc.fetch_size和 hibernate.jdbc.batch_size 25简介
- 交通灯管理系统
- 汉诺塔问题的递归求解
- springMVC文件上传
- 微博估计要火一阵的SleepSort之Shell及C实现
- Clone Graph
- C/C++大文件/数据网络传输方法总结
- PHP正则表达式匹配嵌套HTML标签的方法和技巧
- 【KMP】 HDOJ 3613 Best Reward
- 新手报到
- 序列参数集层(SPS)句法-学习