汉诺塔问题解决方案
#include <stdio.h> #define discCount 4 void move(int, char, char,char); int main() { move(discCount,'A','B','C'); return 0; } void move(int n, char A, char B,char C) { if(n==1) printf("%c-->%c\n", A, C); else { move(n-1,A,C,B); printf("%c-->%c\n", A, C); move(n-1,B,A,C); } }
n个盘子计数
#include <stdio.h> #define discCount 30 long move(int, char, char,char); int main() { long count; count=move(discCount,'A','B','C'); printf("%d个盘子需要移动%ld次\n", discCount, count); return 0; } long move(int n, char A, char B,char C) { long c1,c2; if(n==1) return 1; else { c1=move(n-1,A,C,B); c2=move(n-1,B,A,C); return c1+c2+1; } }
时间: 2024-11-01 01:32:57