汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 cG"<*Xi <
`\uv+^x{
include <iostream> Mj;'vm7#'
#include <stdlib.h> z4UQ:z@
<NsT[r~C
#ifdef _WIN32 |#kf.kN
using namespace std; KD*4n'm!>
#endif +~AI(h
/[T8/7;_l
static void hanoi(int height) !|QeYGnq6
{ 4T^WRS
int fromPole, toPole, Disk; ~ ?_Z!eS
int *BitStr = new int[height], //用来计算移动的盘的号码
%NoZf^?
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 Z'kYf
char Place[] = {'A', 'C', 'B'}; |hyr(7
int i, j, temp; ~ZC=!|Q#
@Ec9Do>
for (i=0; i < height; i++) gJv^v`X
{ (R,n`x2^
BitStr = 0; #-,`4x$m|
Hold = 1; o~>go_Y
} RuuU}XQ
temp = 3 - (height % 2); //第一个盘的柱号 ;VBfzFH
int TotalMoves = (1 << height) - 1; $ wB
for (i=1; i <= TotalMoves; i++) E6)mBAE
{ >,2],X"G
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 03;(v%
{ R>q'Y mu~
BitStr[j] = 0; #pFybk
} '>$A7
BitStr[j] = 1; a{,t@G
Disk = j+1; }y/t~f+
if (Disk == 1) F,:VL*.5kJ
{ !*-cf$
fromPole = Hold[0]; nQ6'yd"
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 ~
$&
temp = fromPole; //保存上一次从哪个柱子移动过来的 5gEK$7Vp
} >o7k%T|l$
else pn|{P<b\
{ de=T7,G#
fromPole = Hold[Disk-1]; Kwnu|8
toPole = 6 - Hold[0] - Hold[Disk-1]; mqw.v$>
} -nSqB{s!SD
cout << "Move disk " << Disk << " from " << Place[fromPole-1] J-c7ZcTt
<< " to " << Place[toPole-1] << endl; "$Q Gifb
Hold[Disk-1] = toPole; 39CPFgi<l*
} 35T7g65;
} CcQ|0
V5MbWXgR
*PPFk.#x
Y8T.RS0
10^=1@U
int main(int argc, char *argv[]) M}u2aW2]X
{ ,sK-gw
cout << "Towers of Hanoi: " << endl d8 po`J#nb
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; ?9"glzxr
cout << "Input the height of the original tower: "; E~ kmU{D
int height; x1h!_^(QfF
cin >> height; O(!'V~3
hanoi(height); QWEK;kUa@
COafVlJ,l
system("PAUSE"); Pc<ZfO #
return EXIT_SUCCESS; teb(\% ,
} pppbn]%Ob
o~B=[
KAZz)7
\b->AXe8
问题描述:有三个柱子A, B, C. A柱子上叠放有n个盘子,每个盘子都比它下面的盘子要小一点,可以从上 z,WrLZC
gqG"t@Y+
到下用1, 2, ..., n编号。要求借助柱子C,把柱子A上的所有的盘子移动到柱子B上。移动条件为:1、一 rxA<\h,A
QHK$
次只能移一个盘子;2、移动过程中大盘子不能放在小盘子上,只能小盘子放在大盘子上。 -_+0[Nb.
S{ !hpq~o
算法要点有二: sQw-#f7t
1、确定哪一个盘子要移动。有n个盘子的Hanoi塔需要移动2^n -1次,设m为n位的二进制数,则m的取值范 hS
Sq=(S
~n?U{
RmH
围为0~2^n -1。让m每次递增1,可以发现,m中最低一位的刚刚由0变为1的位置的位置编号,和即将要移 9z#IdY$a
[Pay<]c6g
动的盘子编号有确定关系。 'J}lnt[V
u|E,Wy1
2、这个盘子往哪个柱子上移。 4p]Y`];U
a.第一次需要移动1号盘,n为奇数时,1号盘首先移动到柱子B,为偶数时首先移动到柱子C。 Z:}^fZP
b.接下来如果移动的盘子不是1号盘。你有两个柱子可以选择。先找到1号盘所在的柱子,因为移动的盘子 a%kj)ah
<[Vr(.A
不能叠放到1号盘上,所以该盘可以移动的位置就是没有1号盘的那个柱子。 8}&cE#@
c.如果移动的盘子是1号盘。也有两个柱子可以选择。找到1号盘原先是从哪个柱子上移来的,因为移动的 HDYf^mcW
v-o/zud]]
顺序(顺时针或逆时针)一旦确定,就不会更改,所以排除from的那个柱子后,移动方向也就唯一了。