今天重新又弄了下汉诺塔算法的学习,具体学习内容如下(有什么不对之处请大家指教指教):
1. 汉诺塔程序的实现:
思路:将n个盘子从A做一道C座可以分解为以下三个步骤:
1)将A上n-1个盘子借助C座线移到B座上;
2)把A座上剩下的一个盘移到C座上;
3)将n-1个盘从B座借助于A座移到C座上。
根据分析,1)和3)都是将n-1个盘从一个座移到另一个座上,采取的办法是一样的,只是座的名字不一样。因此,可以将上面三个步骤分成两类操作:
(1) 将n-1个盘从一个座移到另一个座上(n>1)。
(2) 将一个盘子从一个座上移到另一个座上。
代码如下:
# include <stdio.h>
int moveNum = 0; //记录移动次数
void main()
{
void hanoi(int n, char one, char two, char three);//对hanoi函数的声明
int m;
printf("Please input the number of diskes: ");
scanf("%d", &m);
printf("/n/nThe step to moving %d diskes is: /n/n", m);
hanoi(m, 'A', 'B', 'C');
printf("Total moving number is: %d /n",moveNum);
}
void hanoi(int n, char one, char three, char two)//定义hanoi函数
{//将n个盘从one座借助three座,移到two座
void move(char x, char y, int *j);
if(n == 1)
move(one, three, &moveNum);
else
{
hanoi(n-1, one, three, two);
move(one, three, &moveNum);
hanoi(n-1, two, one, three);
}
}
void move(char x, char y,int *j)//定义move函数,将一个盘子从x座移到y座
{
printf("%c-->%c;/n", x, y);
(*j)++;
}
2. 根据写出的程序可以看出,当只有一块要移动时,我们只需将其移动一次就能到目的座。而当有n块时,程序中要进行双重递归嵌套才能完成移动,也就是我们根据程序得到的递归方程为:
见图片——公式1
3.解递归方程:
见图片——公式2