#include<stdio.h>
void hanoi (int x, char a, char b, char c)
{
if(1 == x)
{
printf("%c-->%c\n", a, c);
}
else
{
hanoi(x - 1, a, c, b); /*x - 1 个盘子从 A 柱移动到 B 柱*/
hanoi(1, a, b, c); /*最大的盘子从 A 柱移动到 C 柱*/
hanoi(x - 1, b, a, c); /*x - 1 个盘子从 B 柱移动到 C 柱*/
}
}
main()
{
int i;
scanf("%d", &i);
hanoi(i, 'A', 'B', 'C');
system("pause");
}
/*
i = 4 的情况分析:
--- hanoi(1, A, C, B);-------> A-->B
--- hanoi(2, A, B, C); --- hanoi(1, A, B, C);-------> A-->C
--- hanoi(1, B, A, C);-------> B-->C
hanoi(3, A, C, B); --- hanoi(1, A, C, B);----------------------------------> A-->B
--- hanoi(1, C, B, A);-------> C-->A
--- hanoi(2, C, A, B); --- hanoi(1, C, A, B);-------> C-->B
--- hanoi(1, A, C, B);-------> A-->B
hanoi(1, A, B, C);-------------------------------------------------------------> A-->C
--- hanoi(1, B, A, C);-------> B-->C
--- hanoi(2, B, C, A); --- hanoi(1, B, C, A);-------> B-->A
--- hanoi(1, C, B, A);-------> C-->A
hanoi(3, B, A, C); --- hanoi(1, B, A, C);----------------------------------> B-->C
--- hanoi(1, A, C, B);-------> A-->B
--- hanoi(2, A, B, C); --- hanoi(1, A, B, C);-------> A-->C
--- hanoi(1, B, A, C);-------> B-->C
*/
希望对你有所帮助。
void hanoi (int x, char a, char b, char c)
{
if(1 == x)
{
printf("%c-->%c\n", a, c);
}
else
{
hanoi(x - 1, a, c, b); /*x - 1 个盘子从 A 柱移动到 B 柱*/
hanoi(1, a, b, c); /*最大的盘子从 A 柱移动到 C 柱*/
hanoi(x - 1, b, a, c); /*x - 1 个盘子从 B 柱移动到 C 柱*/
}
}
main()
{
int i;
scanf("%d", &i);
hanoi(i, 'A', 'B', 'C');
system("pause");
}
/*
i = 4 的情况分析:
--- hanoi(1, A, C, B);-------> A-->B
--- hanoi(2, A, B, C); --- hanoi(1, A, B, C);-------> A-->C
--- hanoi(1, B, A, C);-------> B-->C
hanoi(3, A, C, B); --- hanoi(1, A, C, B);----------------------------------> A-->B
--- hanoi(1, C, B, A);-------> C-->A
--- hanoi(2, C, A, B); --- hanoi(1, C, A, B);-------> C-->B
--- hanoi(1, A, C, B);-------> A-->B
hanoi(1, A, B, C);-------------------------------------------------------------> A-->C
--- hanoi(1, B, A, C);-------> B-->C
--- hanoi(2, B, C, A); --- hanoi(1, B, C, A);-------> B-->A
--- hanoi(1, C, B, A);-------> C-->A
hanoi(3, B, A, C); --- hanoi(1, B, A, C);----------------------------------> B-->C
--- hanoi(1, A, C, B);-------> A-->B
--- hanoi(2, A, B, C); --- hanoi(1, A, B, C);-------> A-->C
--- hanoi(1, B, A, C);-------> B-->C
*/
希望对你有所帮助。