您的位置:首页 > 其它

汉诺塔问题的递归求解

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: