问题概述
有三个座A,B,C,A座上有64个盘子,从下到上盘子逐渐变小。要把这64个盘子从A座移到C座,但每次只能移一个盘子,且在移动过程中三个座上的盘子始终保持大盘在下,小盘在上。
解题步骤
递归方法
- 将A座n-1个盘借助C座移动到B座上;
(借助C座的过程其实就是移动倒数第二个盘的同样的过程) - 把A座剩下一个盘移动到C座上;
- 将n-1个盘从B座借助A座移到C座上。
代码实现
#include "stdafx.h"
int main()
{
void hanoi(int n,char A,char B,char C); //函数声明
int m;
printf("input the number of diskes:");
scanf("%d",&m);
printf("The step to move %d diskes:\n",m);
hanoi(m,'A','B','C');
return 0;
}
void hanoi(int n,char A,char B,char C)
{
void move(char x,char y);
if(n==1) move(A,C); //直到最后只需要移动一个盘子
else
{
hanoi(n-1,A,C,B); //对应步骤1
move(A,C); //对应步骤2
hanoi(n-1,B,A,C); //对应步骤3
}
}
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}