经典算法~~汉诺塔

来源:互联网 发布:lol免费刷金币软件 编辑:程序博客网 时间:2024/05/17 22:14

经典的算法,用递归便可以实现。老到掉牙的算法,但是数不可以很大,太大的话,会一直输出,因为步骤数实在是太大了!~

如果有N个盘子,则需要移动2^N-1次,可想而知有多大了!~

下面是代码:

# include <stdio.h>void han(char x, char y, char z, int n){if(n == 1)printf("num %d form %c to %c\n", n, x, z);else {han(x, z, y, n - 1);printf("num %d form %c to %c\n", n, x, z);han(y, x, z, n - 1);}}int main(){int n;char a = 'A', b = 'B', c = 'C';scanf("%d", &n);han(a, b, c, n);return 0;}
下面是样例:



0 0