初学数据结构,这个是书上的例子
总移动 2^n - 1次
#include <stdio.h>
#include <stdlib.h>
int main()
{
void Towers(int,char,char,char); //前视定义
Towers(4,'A','C','B');
return 0;
}
void Towers(int n,char fromPeg,char toPeg,char auxPeg) // n 个盘子从 fromPeg 借助 auxPeg 移动到 toPeg
{
if(n < 1)
{
exit(0);
}
if(n == 1)
{
printf("disk %d: %c => %c \n",n,fromPeg,toPeg);
}
else
{
Towers(n-1,fromPeg,auxPeg,toPeg);
printf("disk %d: %c => %c \n",n,fromPeg,toPeg); /*这个不明白为什么这么写*/
Towers(n-1,auxPeg,toPeg,fromPeg);
//printf("disk %d: %c => %c \n",n-1,auxPeg,toPeg);
}
}