汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 Mb I';Mq
ijYSYX@
include <iostream> wec|~Rc-
#include <stdlib.h> UeVRd
P2nb&lVdu
#ifdef _WIN32 !2('Cq_^
using namespace std; *lN>RWbM%
#endif &k5 Z|d|
]<0|"NL
static void hanoi(int height) t._W643~
{ <tEN1i
int fromPole, toPole, Disk; Ou
_bM n
int *BitStr = new int[height], //用来计算移动的盘的号码 &&}'
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 ACg5"
char Place[] = {'A', 'C', 'B'}; T[iwP~l
int i, j, temp; |zV-a2K%J
\h%/Cp+p
for (i=0; i < height; i++) x)hp3&L
{ x.7Ln9
BitStr = 0; ?PIOuN=
Hold = 1; K"cN`Kj<*-
} 8"a[W3b
temp = 3 - (height % 2); //第一个盘的柱号 r )cGee
int TotalMoves = (1 << height) - 1; e1dT~l
for (i=1; i <= TotalMoves; i++) 5o~;0K]
{ ^G,]("di`
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 tZtyx;EP
{ (8<U+)[tPy
BitStr[j] = 0; O)'Bx=S4Ke
} pI>i1f=W
BitStr[j] = 1; 4Lx#5}P
Disk = j+1; `N~;X~XFk
if (Disk == 1) /\-qz$
{ k,xY\r$
fromPole = Hold[0]; _u^ S[
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 )g9&fGYf
temp = fromPole; //保存上一次从哪个柱子移动过来的 R4<