汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 3b,=
5 =*@l
include <iostream> )\(lg*?:
#include <stdlib.h> 6NU8HJp
)ynA:LXx
#ifdef _WIN32 e
W9)@nVJ
using namespace std; E*h0#m|)
#endif G[vUOEU~O
p_A5C?&
static void hanoi(int height) OCvml 2
vP
{ %+D-y+hn
int fromPole, toPole, Disk; /E;;j9
int *BitStr = new int[height], //用来计算移动的盘的号码 G3oxa/mO
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 -`,~9y;tx
char Place[] = {'A', 'C', 'B'}; C:WtCAm(
int i, j, temp; >aX:gN
&Jrq5Q C
for (i=0; i < height; i++) vR<fdV
{ M^Q&A R'F
BitStr = 0; buc,M@>
Hold = 1; F]hx
} Z#srQD3].(
temp = 3 - (height % 2); //第一个盘的柱号 zsHG=Ee*
int TotalMoves = (1 << height) - 1; M}R@ K;%
for (i=1; i <= TotalMoves; i++) Qfwwh`;
{ yLV2>kq
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 AECxd[k$9
{ |2WxcW]U.%
BitStr[j] = 0; Q9Q!9B@
} ,<`|-oa
BitStr[j] = 1; pg5@lC]J
Disk = j+1; *Pa2bY3:
if (Disk == 1) &n}8Uw0440
{ QJ[(Y@ O6a
fromPole = Hold[0]; C]aOgt/U
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 ru#T^AI*^
temp = fromPole; //保存上一次从哪个柱子移动过来的 l2z`<2mp
} /e;e\k_}'
else }G"r3*
{ Q>cL?ie
fromPole = Hold[Disk-1]; #nxER
toPole = 6 - Hold[0] - Hold[Disk-1]; U`?zC~
} o'9OPoof:.
cout << "Move disk " << Disk << " from " << Place[fromPole-1] /h{go]&Nb
<< " to " << Place[toPole-1] << endl; rTN"SQt
Hold[Disk-1] = toPole; fRZUY<t
} wghFGHgw
} aNuZ/9O
D}=/w+
~}hba3&b;#
@n5;|`)\
'8]|E
int main(int argc, char *argv[]) AH"g^ gw~T
{ ux"D
]P
cout << "Towers of Hanoi: " << endl Ek gZxT_&
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; n"K {uj))
cout << "Input the height of the original tower: "; bxPY'&