當前位置:編程學習大全網 - 源碼下載 - 求C語言漢諾塔源碼(遞歸和非遞歸都要)

求C語言漢諾塔源碼(遞歸和非遞歸都要)

遞歸算法是我前些天寫的,非遞歸是剛才找的,裏面含遞歸和非遞歸。\x0d\遞歸算法:\x0d\#include \x0d\//遞歸求漢諾塔問題\x0d\void hanoi(int n, char A, char B, char C, int *time)\x0d\{\x0d\if (n>=1)\x0d\{\x0d\ hanoi(n-1, A, C, B, time);\x0d\ move(A, C);\x0d\ (*time)++;\x0d\ hanoi(n-1, B, A, C, time);\x0d\ }\x0d\}\x0d\//打印出每壹步的路徑\x0d\void move(char a, char c)\x0d\{\x0d\printf(" %c-->%c\n", a, c);\x0d\}\x0d\\x0d\int main(void)\x0d\{\x0d\int n, time = 0;;\x0d\printf("請輸入漢諾塔的盤數:");\x0d\scanf("%d", &n);\x0d\printf("%d個盤的漢諾塔移動方法是:", n);\x0d\printf("\n");\x0d\hanoi(n, 'A', 'B', 'C', &time);\x0d\printf("移動了%d次\n", time);\x0d\system("pause");\x0d\return 0;\x0d\}\x0d\\x0d\非遞歸算法:\x0d\#include \x0d\\x0d\#define MAXSTACK 10 /* 棧的最大深度 */\x0d\\x0d\int c = 1; /* 壹個全局變量,表示目前移動的步數 */\x0d\\x0d\struct hanoi { /* 存儲漢諾塔的結構,包括盤的數目和三個盤的名稱 */\x0d\int n;\x0d\char x, y, z;\x0d\};\x0d\\x0d\void move(char x, int n, char y) /* 移動函數,表示把某個盤從某根針移動到另壹根針 */\x0d\{\x0d\printf("%d-> %d from %c -> %c\n", c++, n, x, y);\x0d\}\x0d\\x0d\void hanoi(int n, char x, char y, char z) /* 漢諾塔的遞歸算法 */\x0d\{\x0d\if (1 == n)\x0d\move(x, 1, z);\x0d\else {\x0d\hanoi(n - 1, x, z, y);\x0d\move(x, n, z);\x0d\hanoi(n - 1, y, x, z);\x0d\}\x0d\}\x0d\\x0d\void push(struct hanoi *p, int top, char x, char y, char z,int n)\x0d\{\x0d\p[top+1].n = n - 1;\x0d\p[top+1].x = x;\x0d\p[top+1].y = y;\x0d\p[top+1].z = z;\x0d\}\x0d\\x0d\void unreverse_hanoi(struct hanoi *p) /* 漢諾塔的非遞歸算法 */\x0d\{\x0d\int top = 0;\x0d\\x0d\while (top >= 0) {\x0d\while (p[top].n > 1) { /* 向左走到盡頭 */\x0d\ push(p, top, p[top].x, p[top].z, p[top].y, p[top].n);\x0d\ top++;\x0d\}\x0d\if (p[top].n == 1) { /* 葉子結點 */\x0d\ move(p[top].x, 1, p[top].z);\x0d\ top--;\x0d\}\x0d\if (top >= 0) { /* 向右走壹步 */\x0d\ move(p[top].x, p[top].n, p[top].z);\x0d\ top--;\x0d\ push(p, top, p[top+1].y, p[top+1].x, p[top+1].z, p[top+1].n);\x0d\ top++;\x0d\}\x0d\}\x0d\}\x0d\\x0d\int main(void)\x0d\{\x0d\int i;\x0d\printf("遞歸:\n");\x0d\hanoi(3, 'x', 'y', 'z');\x0d\printf("非遞歸:\n");\x0d\struct hanoi p[MAXSTACK];\x0d\c = 1;\x0d\p[0].n = 3;\x0d\p[0].x = 'x', p[0].y = 'y', p[0].z = 'z';\x0d\unreverse_hanoi(p);\x0d\\x0d\return 0;\x0d\}

  • 上一篇:新人做網站必讀
  • 下一篇:java 繼承,重寫,重載
  • copyright 2024編程學習大全網