汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 "KK}}$>
*Ci&1Mu^Z
include <iostream> q;nAq%
#include <stdlib.h> 13/,^?
ffL]_E
#ifdef _WIN32 plB8iN`x<
using namespace std; 59D'*!l-
#endif !Z2h?..O
rBmW%Gv
static void hanoi(int height) zqdkt `
{ drjNK!XL@
int fromPole, toPole, Disk; ^2Cqy%x-
int *BitStr = new int[height], //用来计算移动的盘的号码 =<H ekiYM
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 G`%rnu
char Place[] = {'A', 'C', 'B'}; @JhkUGG]p
int i, j, temp; 6Zn[l,\
uo]\L^j
for (i=0; i < height; i++) IrCl\HQN
{ =@4,szLO
BitStr = 0; _@XueNU1hS
Hold = 1; )?SF IQ=
} ]@z!r2[
temp = 3 - (height % 2); //第一个盘的柱号 &77J,\C$:
int TotalMoves = (1 << height) - 1; w,j!%N
for (i=1; i <= TotalMoves; i++) n^;-&
{ {ObY1Y`ea
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 h/\Zq
{ OXM=@B<"
BitStr[j] = 0; S;Sy.Lp
} s-Gd{=%/q
BitStr[j] = 1; ;q9Y%*
Disk = j+1; {=
&&J@:
if (Disk == 1) n
Yx[9H N
{ `Z>=5:+G@2
fromPole = Hold[0]; F%y#)53g
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 81|[Y'f
temp = fromPole; //保存上一次从哪个柱子移动过来的 &&<l}E
} Szu@{lpP@
else I/St=-;
{ x'}zNEXI
fromPole = Hold[Disk-1]; K{I "2c
toPole = 6 - Hold[0] - Hold[Disk-1]; IxWi>8
} -V2`[k
cout << "Move disk " << Disk << " from " << Place[fromPole-1] \\R<HuTY
<< " to " << Place[toPole-1] << endl; {f4jE#a>v
Hold[Disk-1] = toPole; _X?_|!;J
} 4>d]0=x
} 8u)>o*
:
k8n9zJ8
sSKD"
)UU`uzU;u
ehr\lcS<
int main(int argc, char *argv[]) 8hww({S2
{ 30I-E._F
cout << "Towers of Hanoi: " << endl u8?$W%eW
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; g ;
-3
cout << "Input the height of the original tower: "; 9
AD*
int height; Da[#X`Kp$
cin >> height; Y]6dYq{k
hanoi(height); KI\bV0$p<
`*Wg&u
system("PAUSE"); L:&