汉诺塔问题的递归求解

来源:互联网 发布: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
原创粉丝点击