汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 h6?^rS8U
.z_nW1id
include <iostream> F?R6zvive
#include <stdlib.h> -rI7ihr*
APF`b
#ifdef _WIN32 PdVx&BL*
using namespace std; MYvz%7
#endif rgCC3TX
MbCz*oW
static void hanoi(int height) eA2*}"W
{ Uz,P^\8^$
int fromPole, toPole, Disk; zeQ~'ao<
int *BitStr = new int[height], //用来计算移动的盘的号码 AZhI~QWo
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 USN'-Ah
char Place[] = {'A', 'C', 'B'}; {$[0YRNk
u
int i, j, temp; 4y+hr
75^*4[
for (i=0; i < height; i++) hz;SDaBA
{ A\rY~$Vr
BitStr = 0; *(q{k%/M
Hold = 1; N?{Zrff2"O
} 6x(b/`VW
temp = 3 - (height % 2); //第一个盘的柱号 <:/aiX8
int TotalMoves = (1 << height) - 1; ag:<%\2c
for (i=1; i <= TotalMoves; i++) T+P{,,a/]
{ ~h8k4eM
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 k7*-v/*S
{ UdkNb}L
BitStr[j] = 0; 7mi*#X}
} ;WN%tI)
BitStr[j] = 1; Pfvb?Hy
Disk = j+1; W3\+51P
if (Disk == 1) `k
I}p
{ XU}i<5
fromPole = Hold[0]; ~!TrC<ft
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 =r]_$r%gR
temp = fromPole; //保存上一次从哪个柱子移动过来的 [*)2Ou
} ^8oN~HLZ
else Lp$&eROFVs
{ ~8k`~t!
fromPole = Hold[Disk-1]; md{1Jn"
toPole = 6 - Hold[0] - Hold[Disk-1]; ?P7QAolrr
} B\AyG4J
cout << "Move disk " << Disk << " from " << Place[fromPole-1] SP2";,%/9
<< " to " << Place[toPole-1] << endl;
2i6P<&@
Hold[Disk-1] = toPole; epk
C'
} nrpbQ(zI*
} t9W* N\
O[1Q#
?=iy 6q
d<\X)-"
0""%@X]m
int main(int argc, char *argv[]) 65&+Fv
{ TffeCaBv
cout << "Towers of Hanoi: " << endl bsc b
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; !C' Y
7
cout << "Input the height of the original tower: "; }236{)DuN
int height;
6 ;\>,
cin >> height; O'k<4'TC
hanoi(height); +@Kq
JKYl
system("PAUSE"); Jn0L_@
return EXIT_SUCCESS; zBrqh9%8e
} `$;%%/tx
g fv?#mp
w~9Y=|YI7
G8W^XD
问题描述:有三个柱子A, B, C. A柱子上叠放有n个盘子,每个盘子都比它下面的盘子要小一点,可以从上 ,tFLx#e#
<