汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 W|~Lmdzj
~Bn#AkL
include <iostream> Q(gu";&
#include <stdlib.h> j['Z|Am"l
{y=H49
#ifdef _WIN32 fKIwdk%!-
using namespace std; nU%rSASu
#endif ftsr-3!Vm
%b'ic
static void hanoi(int height) Y[Us"K`
{ *>rpcS<l
int fromPole, toPole, Disk; ?sDm~]Z
int *BitStr = new int[height], //用来计算移动的盘的号码 ORlz1&hW
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 yi%A*q~MT
char Place[] = {'A', 'C', 'B'}; By6C+)up
int i, j, temp; /lDW5;d
& PrV+Lv
for (i=0; i < height; i++) YnuC<y
&p
{ K$(&Qx}
BitStr = 0; eSoOJ[&$
Hold = 1; h>$,97EU
} ~|@ aV:k
temp = 3 - (height % 2); //第一个盘的柱号 gE(QVbh(
int TotalMoves = (1 << height) - 1; 9+h9]T:9
for (i=1; i <= TotalMoves; i++) N:[m,U9a
{ ^"K
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 MX6*waQ-<
{ r Y|'<$wvg
BitStr[j] = 0; R+8+L|\wHv
} Xj"/6|X
BitStr[j] = 1; W&}YMb
Disk = j+1; fGb(=l
if (Disk == 1) 5.F.mUO
{ DSYtj}>
fromPole = Hold[0]; r
vVU5zA4H
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 xeo;4c#S5
temp = fromPole; //保存上一次从哪个柱子移动过来的 $&nF1HBI4