汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 myZ8LQ&
-s:NF;"
include <iostream> j&,%v+x
#include <stdlib.h> S'q4va"
04#r'UIF
#ifdef _WIN32 =I)Ex)
using namespace std; _M[T8 "e(
#endif (ZK(ODn)i
_8?r!D#P;s
static void hanoi(int height) f{R/rb&iB
{ pW2-RHGJY
int fromPole, toPole, Disk; \XG\
int *BitStr = new int[height], //用来计算移动的盘的号码 'n!Sco)C
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 5'"9)#Ve
char Place[] = {'A', 'C', 'B'}; #tt*yOmiH
int i, j, temp; Ni61o?]Nj
mk?F+gh
for (i=0; i < height; i++) #xxs^Kbqa#
{ gG46hO-M%x
BitStr = 0; y/Q,[Uzk\
Hold = 1; |uln<nM9
} +dK;\wT
temp = 3 - (height % 2); //第一个盘的柱号 (wEaw|Zx
int TotalMoves = (1 << height) - 1; G~\=:d=^,`
for (i=1; i <= TotalMoves; i++) (fnp\j3w
{ f.u+({"ql
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 ^Hv4t
{ _i1x\Z~
N
BitStr[j] = 0; kT{d pGU9
} f!##R-A
BitStr[j] = 1; G(7WUMjl
Disk = j+1; 9GVv[/NAb
if (Disk == 1) q*K.e5"'
{ o[K,(
fromPole = Hold[0]; }JBLzk5|
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 {o.i\"x;
temp = fromPole; //保存上一次从哪个柱子移动过来的 +#
tmsv]2
} 1bJrEXHXy
else #ZpR.$`k
{ i}e OWi
fromPole = Hold[Disk-1]; x-=qlg&EI
toPole = 6 - Hold[0] - Hold[Disk-1]; dy2<b+..
} SH M@H93
cout << "Move disk " << Disk << " from " << Place[fromPole-1] <bgFc[Z
<< " to " << Place[toPole-1] << endl; 6
VuMx7W1
Hold[Disk-1] = toPole; $"x~p1P
} =!|=Y@
} *z\L
HFrwf{J
JG!@(lr
yixAG^<