汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 ~~ty9;KYL
|ew:}e: k<
include <iostream> t$Ua&w
#include <stdlib.h> bG)6p05Oa
U[@B63];0
#ifdef _WIN32 $T2zs$
using namespace std; 2+LvlS)C
#endif t{ridA}
I?<ibLpX
static void hanoi(int height) v[m1R'
{ I]d?F:cdX
int fromPole, toPole, Disk; ,=}+.ax
int *BitStr = new int[height], //用来计算移动的盘的号码 -dUXd<=ue
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 8O*O5
char Place[] = {'A', 'C', 'B'}; KH[Oqd
int i, j, temp; 1a},(ZcdX
IS!]!s'EI
for (i=0; i < height; i++) vmtmiN8;d
{ %vrUk;<35
BitStr = 0; xSjs+Y;Mu
Hold = 1; 072`i46
} -.vNb!=
temp = 3 - (height % 2); //第一个盘的柱号 sJLJVSv8c
int TotalMoves = (1 << height) - 1; V ;M'd@
for (i=1; i <= TotalMoves; i++) `&A-m8X
{ O@KAh5EB
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 *>Zq79TG
{ of.=n
BitStr[j] = 0; (Yc}V
} 7:S)J~s*O
BitStr[j] = 1; 4*+)D8
Disk = j+1; rEZMX2
if (Disk == 1) e&="5.ik
{ 8~h.i1L
fromPole = Hold[0]; *U4eL-
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子
zQ,ymfT
temp = fromPole; //保存上一次从哪个柱子移动过来的 #c2JWDH1F
} pS)/yMlVj
else qznd'^[
{ +t;j5\HS
fromPole = Hold[Disk-1]; e_CgZ
toPole = 6 - Hold[0] - Hold[Disk-1]; Qc"UTvq
} J$i5A9IUr
cout << "Move disk " << Disk << " from " << Place[fromPole-1] W6uz
G
<< " to " << Place[toPole-1] << endl; H9T'{R*FC
Hold[Disk-1] = toPole; A!!W\Jt
} 5ayH5=(t
} mE_?E&T`|
Y[ toN9,
d+Jj4OnP
_n_|skG
VSa#X |z
int main(int argc, char *argv[]) pWXoJ0N
{ o%=OBTh_
cout << "Towers of Hanoi: " << endl =P<7tsSuoK
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; N;]"_"
cout << "Input the height of the original tower: "; PWThm ooP
int height; bIahjxd:
cin >> height; %,G0)t
hanoi(height); ~!a~ -:#
1-60gI1)
system("PAUSE"); (Y%pk76d
return EXIT_SUCCESS; hbv>Jjd
} .#y.:Pb|e
\"@BZ.y
ht%:e?@i
Y-Gqx
问题描述:有三个柱子A, B, C. A柱子上叠放有n个盘子,每个盘子都比它下面的盘子要小一点,可以从上 +\n8##oAI
VCZ.{MD
到下用1, 2, ..., n编号。要求借助柱子C,把柱子A上的所有的盘子移动到柱子B上。移动条件为:1、一 +
\AiUY
J}cqBk>
次只能移一个盘子;2、移动过程中大盘子不能放在小盘子上,只能小盘子放在大盘子上。 (\<