汉罗塔问题:ios
有三个柱子A,B,C,在A中有n个从底部到顶部逐渐减少的盘子,如今要将A柱的盘子移动到C中去,而且在C中也是要从底部开始逐渐减少排列的。算法
这是个典型的经过递归来解决的问题,在使用递归算法时,this
咱们首先要找到anchor,在此例中,anchor就是:当n = 1时,也就是只移动一个盘子时,那就是从A柱移动一个盘子到C盘去。若是是n个盘子呢?那咱们首先移动n-1个盘子到B柱去,而后再将A最后一个盘子移到C柱去,最后再将B柱的n-1个盘子移动到C柱去。spa
因此算法以下:code
#include <iostream> #include <iomanip> using namespace std; void move(unsigned n, unsigned &moveNumber, char source, char destination, char spare) { if (n == 1) {//anchor moveNumber++; cout << setw(3) << moveNumber <<". move the top disk from " << source << " to " << destination << endl; } else {//移动n-1个盘子 move(n-1, moveNumber, source, spare, destination);//先移动n-1个盘子到B move(1, moveNumber, source, destination, spare);//在将A最后的一个移动到C move(n-1, moveNumber, spare, destination, source);//再将B的n-1个盘子移动到C } } int main() { const char PEG1 = 'A', PEG2 = 'B', PEG3 = 'C'; unsigned moveNumber = 0; cout << "this programe solves the hanno tower puzzle.\n\n" << endl; cout << "enter the number of disk:" << endl; int numdisks; cin >> numdisks; move(numdisks, moveNumber, PEG1, PEG2, PEG3);//递归算法 return 0; }