汉诺塔问题的递归求解
2014-06-29 15:28
381 查看
/**
* 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. */ PEGTYPE rest; 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 int count = 0; printf("[%4d] %d-->%d \n", count, from, to); count ++; return true; } int main( ) { HanoiT han; han.solve( PT_A, PT_C, 4); return 0; }
相关文章推荐
- 用递归方法求解汉诺塔问题。
- 从“递归结构”到解汉诺塔问题的求解
- 学习C/C++语言:递归求解hanoi汉诺塔问题
- 采用递归和非递归方法求解汉诺塔问题
- 用递归法:设计算法求解汉诺塔问题,并编程实现。 (1) Hanoi(汉诺)塔问题分析 这是一个古典的数学问题,是一个用递归方法解题的典型例子。问题是这样的:古代有一个梵塔,塔内有3个座 A,B,C
- Java编程用栈来求解汉诺塔问题的代码实例(非递归)
- 汉诺塔问题递归求解(python)
- java中使用递归求解汉诺塔问题
- 黑马程序员--汉诺塔问题的递归求解C语言
- 1_6_1用栈求解汉诺塔问题_利用递归求解增强版汉诺塔问题
- 汉诺塔问题递归求解
- C语言实现Hanoi(汉诺塔)问题的递归求解
- 用递归方法求解汉诺塔问题
- 汉诺塔(Tower of Hanoi)问题的求解——利用栈与递归
- Java经典编程300例之实例047 汉诺塔问题求解(递归)
- 数据结构学习之递归求解汉诺塔问题
- 汉诺塔问题的递归求解
- 递归求解汉诺塔问题
- 汉诺塔问题(递归求解)
- 学习笔记---递归的代码,解决经典的汉诺塔问题