汉诺塔非递归算法.我只是将盘子的数量等于2,3的情况代到网上别人给的算法中验证了一下,没有错。并没有证明算法的正确性。算法是否有效,有待大家证明。 #u+BjuZo
lh`inAt)"
include <iostream> A(AyLxB47*
#include <stdlib.h> @~6A9Fr
-k\7k2
#ifdef _WIN32 )f#@`lf[<
using namespace std; Y{y #us1
#endif ^EU&6M2
'R6D+Vk/
static void hanoi(int height) @'[w7HsJ
{ QI>yi&t
int fromPole, toPole, Disk; QC>I<j&`!
int *BitStr = new int[height], //用来计算移动的盘的号码 'qLk"
*Hold = new int[height]; //用来存贮当前的盘的位置。hold[0]为第一个盘所在的柱号 j9C=m"O
char Place[] = {'A', 'C', 'B'}; S8j;oJ2d
int i, j, temp; R= HN>(U
S|T:rc(~
for (i=0; i < height; i++) [;dWFG"f
{ UNocm0!N'
BitStr = 0; @%J?[PG
Hold = 1; bTC2Ya
} )>at]mH
temp = 3 - (height % 2); //第一个盘的柱号 BXueOvO8
int TotalMoves = (1 << height) - 1; 1DcYc-k#
for (i=1; i <= TotalMoves; i++) jM
J[6qj
{ "d'xT/l
"
for (j=0 ; BitStr[j] != 0; j++) //计算要移动的盘 yZI4%fen
{ ZTd_EY0 q
BitStr[j] = 0; G~)jk+Qq
} 'ntb.S)
BitStr[j] = 1; *sf9(%j
Disk = j+1; ] d| -r:4
if (Disk == 1) :YjOv
{ Tp~yn
fromPole = Hold[0]; !Dkz6B*
toPole = 6 - fromPole - temp; //1+2+3等于6,所以6减去其它两个,剩下那个就是要移去的柱子 mh44
temp = fromPole; //保存上一次从哪个柱子移动过来的 d%9I*Qo0,
} n);2b\&
else S|;a=K&hS
{ XRs/gUT
fromPole = Hold[Disk-1]; Ed#%F-1sX
toPole = 6 - Hold[0] - Hold[Disk-1]; EH3jzE3N
} g2C-)*'{yh
cout << "Move disk " << Disk << " from " << Place[fromPole-1] `ZN@L<I6
<< " to " << Place[toPole-1] << endl; =Z/'|;Vd_x
Hold[Disk-1] = toPole; ` 2|~Z
H
} hX)r%v:
} -a3+C,I8g
fh$U"
/@FB;`'
5`oor86
k}>l+_*+7
int main(int argc, char *argv[]) 05*_h0}
{ 'DsfKR^s
cout << "Towers of Hanoi: " << endl v Xio1hu
<< "moving a tower of n disks from pole A to pole B by using pole C" << endl; [k-7Kq
cout << "Input the height of the original tower: "; 8q7KqYu
int height; f]$g9H
cin >> height; L3q)j\ls
hanoi(height); "r cPJX
<)Kjf/x
system("PAUSE"); T'XAcH
return EXIT_SUCCESS; (#c5Q&