汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 28LYGrB
Pd;G c@'~
include <iostream> EM,=R
#include <stdlib.h> y=SVS3D
J1@skj4#\~
#ifdef _WIN32 !:M+7kmr7t
using namespace std; KLgg([
#endif YU/?AQg
nG0R1<
static void hanoi(int height) \"6?*L|]
{ )_SpY\J
int fromPole, toPole, Disk; k[{ ~eN:
int *BitStr = new int[height], //用来计算移动的盘的号码 ~ ;ObT=
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 |X;|=.
char Place[] = {'A', 'C', 'B'}; y'm5Z-@o6
int i, j, temp; 8\HzFB
*g[MGyF"
for (i=0; i < height; i++) %{&,5|8
{ 59BB-R,V
BitStr = 0; 9E}JtLgT
Hold = 1; MM(\>J[Uq
} a6\`r^ @
temp = 3 - (height % 2); //第一个盘的柱号 eD!mR3Ai@D
int TotalMoves = (1 << height) - 1; *1,4#8tB
for (i=1; i <= TotalMoves; i++) IO<Ds#(
{ Ix+eP|8F
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 0HN%3AG]
{ %{ory5
BitStr[j] = 0; #|=Q5"wU
} /cZTj!M
BitStr[j] = 1; hRZYvZ3
Disk = j+1; 8~y&" \
if (Disk == 1) ew<_2Xy"<
{ cc 0Tb
fromPole = Hold[0]; 'PWA
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 @S1Z"%S
temp = fromPole; //保存上一次从哪个柱子移动过来的 Ty} Y/jW
} @;}vK=6L
else H
h35cj
{ __}ut+H^5p
fromPole = Hold[Disk-1]; l"/E,X
toPole = 6 - Hold[0] - Hold[Disk-1]; HJJ;gTj
} O~mQ\GlW
cout << "Move disk " << Disk << " from " << Place[fromPole-1] 2WC$r8E
<< " to " << Place[toPole-1] << endl; *U +<Hv`C
Hold[Disk-1] = toPole; jc HyRR1R
} fNz(z\
} gFl@A}
"EwzuM8f
h 27f0x9
^0 &jy:{
iP6?[pl8
int main(int argc, char *argv[]) NuW6~PV
{ hR~&}sxN
cout << "Towers of Hanoi: " << endl d'iSvd.
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; D7=Irz!O\7
cout << "Input the height of the original tower: "; !6,rN_a@Y
int height; T"1=/r$Ft
cin >> height; X.ecA`0
hanoi(height); [,(+r7aB
}m&\I
system("PAUSE"); S_?sJwM
return EXIT_SUCCESS; Po*!eD
} & H8 %
6sG5n7E-A
&