汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 or7l}X
&a\G,Ma
include <iostream> EVLDP\w{
#include <stdlib.h> F<*zL:-Z
IkGM~3e
#ifdef _WIN32 ,Vz-w;oDn
using namespace std; R-4#y%k<
#endif Gsm.a
C8(0|XX
static void hanoi(int height) AmCymT3P*e
{ {9Q**U`w
int fromPole, toPole, Disk; e%7#e%1s
int *BitStr = new int[height], //用来计算移动的盘的号码 VjeF3pmBa
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 T=g2gmo9
char Place[] = {'A', 'C', 'B'}; 7o7FW=^
int i, j, temp; 1@~ 1vsJ
usi3z9P>n
for (i=0; i < height; i++) Tx'anP
{ @j(2tJ,w
BitStr = 0; dtV7YPz4+
Hold = 1; lXVh`+X/l
} 52'6wwv6?
temp = 3 - (height % 2); //第一个盘的柱号 7WNUHLEt
int TotalMoves = (1 << height) - 1; _0iV6Bj
for (i=1; i <= TotalMoves; i++) j5~~%
{ a`U/|[JM
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 (7??5gjh
{ |`AJP
BitStr[j] = 0; eK\i={va
} '_91(~P
BitStr[j] = 1; og4mLoLA
Disk = j+1; @qF:v]=_@
if (Disk == 1) 4 *.
O%
{ JEeXoGKd
fromPole = Hold[0]; >``
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 owA.P-4
temp = fromPole; //保存上一次从哪个柱子移动过来的 1>bNw-kz7
} J7kqyo"
else ''p<C)Q
{ m:9|5W
fromPole = Hold[Disk-1]; ;):E 8;B)
toPole = 6 - Hold[0] - Hold[Disk-1]; 12tAx3p
} !&{"tL@.
cout << "Move disk " << Disk << " from " << Place[fromPole-1] 3/,}&SX
<< " to " << Place[toPole-1] << endl; }Am5b@g"$Y
Hold[Disk-1] = toPole; X#fjIrn
} ]na$n[T/I
} nIfp0U*
1q|iw
xg'xuz$U
rG%8ugap
^SIA%S3
int main(int argc, char *argv[]) )E^Pn|H
{ G4\|bwh
cout << "Towers of Hanoi: " << endl y#/P||PM
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; MIqH%W.ru
cout << "Input the height of the original tower: "; -\25&m!+
int height; UsdMCJ&G
cin >> height; $3cZS
hanoi(height); Io{BO.K*Y
MieO1l
system("PAUSE"); &