汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 [=q/f2_1.
{Fw"y %a^
include <iostream> %N<5ST>(
#include <stdlib.h> 208^Yu
c2M
#ifdef _WIN32 m]>zdP+
using namespace std; JpC=ACF
#endif 9Sxr9FLW~
=IsmPQKi
static void hanoi(int height) _90D4kGU
{ },l
i'r#p
int fromPole, toPole, Disk; (is' ,4^b
int *BitStr = new int[height], //用来计算移动的盘的号码 $e7%>*?m
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 3P2{M}WIl
char Place[] = {'A', 'C', 'B'}; W4^zKnH
int i, j, temp; g&xj(SMj-$
{f#QZS!E
for (i=0; i < height; i++) Ul_Zn
{ S9Yzvq!(
BitStr = 0; Qq`S=:}~x
Hold = 1; H@1'El\9
} ?Te#lp;`~
temp = 3 - (height % 2); //第一个盘的柱号 Za{O9Qc?D|
int TotalMoves = (1 << height) - 1; yogavCD9b/
for (i=1; i <= TotalMoves; i++) 1Z< ^8L<
{ ]|CcQ1#|H
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 l&+O*=#Hh
{ 1 Q(KZI
BitStr[j] = 0; ?K[Y"*y2
} @^UgdD,BS,
BitStr[j] = 1; FE!jN-#
Disk = j+1; +Pl)E5W!=`
if (Disk == 1) R QQ'Wg
{ _HHvL=
fromPole = Hold[0]; q8d](MaX
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 dXh[Ea^
temp = fromPole; //保存上一次从哪个柱子移动过来的 t8-Nli*O
} paIjXaU1Mb
else {O2=K#J
{ $UH:r
fromPole = Hold[Disk-1]; kFp^?+WI%H
toPole = 6 - Hold[0] - Hold[Disk-1]; Nz2V aZ
} /Yy)=~t{
cout << "Move disk " << Disk << " from " << Place[fromPole-1] 7?whxi Qs
<< " to " << Place[toPole-1] << endl; )&1v[]%S
Hold[Disk-1] = toPole; S=r0tao,!v
} q*
R}yt5
} %@vF%
n\((#<&
m~
ah!QM
uM`i!7}
Ih:Q}V#6
int main(int argc, char *argv[]) Pjs=n7
{ JW[6
^Rw
cout << "Towers of Hanoi: " << endl VEh9N
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; g& e u
cout << "Input the height of the original tower: "; @bA5uY!
int height; J]TqH`MA
cin >> height; cOV9g)7^O
hanoi(height); rgVRF44X{
&K0b3AWc
system("PAUSE"); Wz'!stcp
return EXIT_SUCCESS; hEB5=~A_
} 0vjCSU-X
b~vV++ou_
YYn8!FIe
**h4M2'C
问题描述:有三个柱子A, B, C. A柱子上叠放有n个盘子,每个盘子都比它下面的盘子要小一点,可以从上 q|<B9Jk
v`,!wS
到下用1, 2, ..., n编号。要求借助柱子C,把柱子A上的所有的盘子移动到柱子B上。移动条件为:1、一 !0@4*>n
?{ExBZNa
次只能移一个盘子;2、移动过程中大盘子不能放在小盘子上,只能小盘子放在大盘子上。 BjfVNF;hk:
^ 4<