汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 VArMFP)cz
,}Im^~5
include <iostream> zYftgH_o
#include <stdlib.h> /c7jL4oD
!4YmaijeN
#ifdef _WIN32 N)KN!!
using namespace std; <jLL2-5r0
#endif w.=rea~
4NIb_E0
static void hanoi(int height) i&)OJy
{ 8>X] wA6q
int fromPole, toPole, Disk; m*KI'~#$%
int *BitStr = new int[height], //用来计算移动的盘的号码 G12o?N0p
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 %F:; A
char Place[] = {'A', 'C', 'B'}; g12.4+
int i, j, temp; fA ),^
/\E3p6\*
for (i=0; i < height; i++) nD=N MqQ &
{ 1IK*j+%
BitStr = 0; F 9q!Upr_+
Hold = 1; ~P*{%= a
} Ve40H6Ox
temp = 3 - (height % 2); //第一个盘的柱号 H*",'`|-
int TotalMoves = (1 << height) - 1; W4nhPH(
for (i=1; i <= TotalMoves; i++) ;g<y{o"Q3p
{ ~O3VX75f
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 SkU9iW(k
{ mZjP;6
BitStr[j] = 0; b$`/f:_
} RgzzbW
BitStr[j] = 1; e
:@PI(P!
Disk = j+1; >;fn,9w
if (Disk == 1) 4-C'2?
{ sAF="uB
fromPole = Hold[0]; F-D$Y?m
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 t\n'Kuk`
temp = fromPole; //保存上一次从哪个柱子移动过来的 2>Qy*
} }CrWmJu0
else i=V2
/W}
{ w@a|_?
fromPole = Hold[Disk-1]; ')(U<5y)
toPole = 6 - Hold[0] - Hold[Disk-1]; $3eoZ1q'U-
} VpED9l]y
cout << "Move disk " << Disk << " from " << Place[fromPole-1] c/Li,9cT'
<< " to " << Place[toPole-1] << endl; Zk31|dL
Hold[Disk-1] = toPole; Bc<