汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 k<!<<,Z
xF&6e&nv
include <iostream> ]}.0el{
#include <stdlib.h> VXA[TIqp
f#1/}Hq/I
#ifdef _WIN32 Cc2MYm8
using namespace std; b(/j\NWC
#endif [M`=HhJ4
XJc
,uj7
static void hanoi(int height) C1tb`
{ UAdz-)$
int fromPole, toPole, Disk; hv3;irK]&
int *BitStr = new int[height], //用来计算移动的盘的号码 <Kg2$lu(_`
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 ><cU7 ja[^
char Place[] = {'A', 'C', 'B'}; hzv3F9.x
int i, j, temp; v_.HGGS
0JK2%%
for (i=0; i < height; i++) +N7"EROc
{ w\Iqzpikr
BitStr = 0; vf[&7n
Hold = 1; ![
a
} dIvy!d2l
temp = 3 - (height % 2); //第一个盘的柱号
>9{zQf!
int TotalMoves = (1 << height) - 1; Z/gsCYS3F
for (i=1; i <= TotalMoves; i++) BGN9,ii
{ !W~QT}
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 ,[Ag~.T
{ 1&|
BitStr[j] = 0; EsTB(9c?
} mzz$`M1
BitStr[j] = 1; f9a$$nb3`
Disk = j+1; >otJF3zw
if (Disk == 1) ?.Q3 pUT
{ iKhH ^V%j
fromPole = Hold[0]; *Z; r
B
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 V3Yd&HVWNQ
temp = fromPole; //保存上一次从哪个柱子移动过来的 G0Hs,B@5?
} 1 =^
else ?,>5[Ha^?
{ S@Iw;V
fromPole = Hold[Disk-1]; "oe!M'aj`1
toPole = 6 - Hold[0] - Hold[Disk-1]; @7%.7LK
} i-]U+m*
cout << "Move disk " << Disk << " from " << Place[fromPole-1] \ADLMj`F|
<< " to " << Place[toPole-1] << endl; (n,N8k;
Hold[Disk-1] = toPole; $~G@
} ;
h85=l<8u
} 'AWp6L @
F 5U|9<
sBU_Ft
Wxn#Rk#>
JCD?qeTg
int main(int argc, char *argv[]) $it@>L8
{ !9D1
Fa
cout << "Towers of Hanoi: " << endl p31oL{D
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; >azEed<B
cout << "Input the height of the original tower: "; 6}#"qqnx
int height; 8ljuc5,J
cin >> height; uFo/s&6K
hanoi(height); lm*g Gy1i
2T?TM! \Q
system("PAUSE"); 0<Q*7aY
return EXIT_SUCCESS; z&F5mp@
} +?Ez}
BP
7h`^N5H.q
'60//"9>k/
nA+F
问题描述:有三个柱子A, B, C. A柱子上叠放有n个盘子,每个盘子都比它下面的盘子要小一点,可以从上 F,&