Hanoi(汉诺)塔问题。古代有一个焚塔,塔内有3个座A,B,C,开始时A座上有64个盘子,盘子大小不等,大的在上,小的在下,有一个老和尚想把这64个盘子从A座移到C座,但规定每次只允许移到一个盘,且在移动过程中在3个座上都始终保持大盘在下,小盘在上,在移动过程中可以利用B座。输出移动盘子的步骤。

解:由于64个盘子移动步骤太多,本程序以3个盘子为例进行输出

程序:

 

#include<stdio.h>


void hanoi(int n,char one,char two,char three)

{

void move(char x, char y);

if (n ==1)

{

move(one,three);

}

else 

{

hanoi(n-1,one,three,two);

move(one, three);

hanoi(n - 1, two, one, three);

}

}


void move(char x, char y)

{

printf("%c-->%c\n", x, y);

}


int main()

{

int n;

printf("input the number of diskes:");

scanf("%d", &n);

printf("The step to move %d diskes:\n",n);

hanoi(n, 'A', 'B', 'C');

return 0;

}

结果:

input the number of diskes:3

The step to move 3 diskes:

A-->C

A-->B

C-->B

A-->C

B-->A

B-->C

A-->C

请按任意键继续. . .