汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 szW85{<+
fkmN?CU{1%
include <iostream> >V1v.JH
#include <stdlib.h> Y6r<+#V
A9L
{c!|-
#ifdef _WIN32 F;;\I
using namespace std; %an&lcoX
#endif C!Oz'~l
.PJCBTe
static void hanoi(int height) LIZsDTU
{ j`A 3N7;
int fromPole, toPole, Disk; -"Hy%wE
int *BitStr = new int[height], //用来计算移动的盘的号码 ~v+A6N:qC
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 0.}WZAYy~
char Place[] = {'A', 'C', 'B'}; ygn]f*;?kw
int i, j, temp; QKt[Kte
YD|;xuh
for (i=0; i < height; i++) Nn]|#lLP
{ WfF~\DlrD
BitStr = 0; pNIu;1M5a
Hold = 1; N);2 2-
} {, `)
temp = 3 - (height % 2); //第一个盘的柱号 [c_o.`S_\
int TotalMoves = (1 << height) - 1; oe*Y(T\G
for (i=1; i <= TotalMoves; i++) 27q=~R}
{ [~#]p9|L
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 ql_GN[c/
{ =@EX!]=x
BitStr[j] = 0; (h3f$
} Oj ?
|g_
BitStr[j] = 1; IGC:zZ~z
Disk = j+1; O${B)C,
if (Disk == 1) OELh6R
{ ~M!s0jT
fromPole = Hold[0]; i{+W62k*
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 Sdn4y(&TP
temp = fromPole; //保存上一次从哪个柱子移动过来的 Td"_To@jd
} "cVJqW
else ]> dCt<
{ 0l&#%wmJ,
fromPole = Hold[Disk-1]; a(BEm_l3
toPole = 6 - Hold[0] - Hold[Disk-1];
ndCHWhi
} *[SOz)
cout << "Move disk " << Disk << " from " << Place[fromPole-1] PUJkC
<< " to " << Place[toPole-1] << endl; 48 n5Y~YS
Hold[Disk-1] = toPole; gcKXda(
} >.X& v
} ?\7$63gBH
!:<(p
#Z)8,N
aUTXg60l*
ta'{S=^j
int main(int argc, char *argv[]) 'W2B**}
{ ?7]UbtW[
cout << "Towers of Hanoi: " << endl / 80Q
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; 2Sg^SZFH+o
cout << "Input the height of the original tower: "; q{:]D(
int height; nhZ^`mP
cin >> height; v3q.,I_
hanoi(height); nS5g!GYY,k
b|KlWt'
system("PAUSE"); f0d*%
return EXIT_SUCCESS; }mx>3G{d
} <