汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 q~5zv4NX
1a V32oK
include <iostream> iGz*4^%
#include <stdlib.h> hmOGteAf-
J Eo;Fx]
#ifdef _WIN32 m;hp1VO)
using namespace std; &+A78I
#endif ks6iy}f7
: _:)S
static void hanoi(int height) %72(gR2Wa2
{ 3 yb]d5:U
int fromPole, toPole, Disk; M%Rr=
int *BitStr = new int[height], //用来计算移动的盘的号码 ]+m2pEO
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 >o{JG(Rn
char Place[] = {'A', 'C', 'B'}; 4e .19H9
int i, j, temp; \P9ms?((A
=)c-Xz
for (i=0; i < height; i++) <82&F
{ SCe$v76p#
BitStr = 0; r-xP6
Hold = 1; WFV'^-4
} *` wz
temp = 3 - (height % 2); //第一个盘的柱号 ,%N[FZ`|
int TotalMoves = (1 << height) - 1; xP9h$!
for (i=1; i <= TotalMoves; i++) febn?|@
{ u/S>*E
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 w xte
{ |[mmEYc
BitStr[j] = 0; <%%)C>l
} d0ht*b
BitStr[j] = 1; !X$19"
Disk = j+1; H
lM7^3(&
if (Disk == 1) ~Js kA5h|&
{ mVYfyLZ,(
fromPole = Hold[0]; R"JXWw
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 3@ Fa
temp = fromPole; //保存上一次从哪个柱子移动过来的 <]KQ$8dtD
} trrK6(p
else z_lKq}^~6
{ *s"OqTM]x
fromPole = Hold[Disk-1]; na8`V`77
toPole = 6 - Hold[0] - Hold[Disk-1]; IzUpkwN
} EirZ}fDJzB
cout << "Move disk " << Disk << " from " << Place[fromPole-1] 7)[Ve1;/N
<< " to " << Place[toPole-1] << endl; +[MHl
Hold[Disk-1] = toPole; tu$rVwgM
} DUl+Jqn4B
} "+7E9m6I
1:^Xd~X
Dt(D5A
OaY89ko
+swT MR
int main(int argc, char *argv[]) V>Z4gZp5sc
{ U_izKvEh
cout << "Towers of Hanoi: " << endl :Z2997@Y
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; @#N7M2/
cout << "Input the height of the original tower: "; PWx%~U.8~j
int height; ;n*|AL7(
cin >> height; sF[gjeIb
hanoi(height); ?<