Demo:Hanoi塔問題到底是如何啟動並執行?,demohanoi
Hanoi問題以遞迴移動柱上碟子的方法解決問題,但各柱上碟片的變化到底是如何變化的?
下面的程式給出了示範效果,便於程式員理解。
#include <stdio.h>#define N 6int Vals[3][N+1]; int movecnt = 0;void out() {for(int i = 0; i < 3; i++) {for(int j = 1; j <= N; j++)if (j <= Vals[i][0])printf("%d ", Vals[i][j]);elseprintf(" ");printf("\t");}printf("\n");movecnt++;}void move(int a, int c) {int na = Vals[a][0];int nc = Vals[c][0];int v = Vals[a][na];nc++;Vals[c][nc] = v;Vals[c][0] = nc;na--;Vals[a][0] = na;out();}void hanoi(int n, int A, int B, int C) { if(n == 1) { move(A , C); } else { hanoi(n - 1 , A , C , B); move(A , C); hanoi(n - 1 , B , A , C); }}int main() {Vals[0][0] = N;Vals[1][0] = 0;Vals[2][0] = 0;for(int i = 1; i <= N; i++)Vals[0][i] = N - i + 1;printf("A\t\tB\t\tC\n");out();hanoi(N, 0, 1, 2);out();printf("移動次數:%d\n", movecnt);return 0;}程式運行結果:
A B C
6 5 4 3 2 1
6 5 4 3 2 1
6 5 4 3 1 2
6 5 4 3 2 1
6 5 4 3 2 1
6 5 4 1 3 2
6 5 4 1 3 2
6 5 4 3 2 1
6 5 3 2 1 4
6 5 3 2 4 1
6 5 2 3 4 1
6 5 2 1 3 4
6 5 2 1 4 3
6 5 2 1 4 3
6 5 1 4 3 2
6 5 4 3 2 1
6 5 4 3 2 1
6 1 5 4 3 2
6 1 5 2 4 3
6 5 2 1 4 3
6 3 5 2 1 4
6 3 5 2 4 1
6 3 2 5 4 1
6 3 2 1 5 4
6 3 2 1 5 4
6 3 2 5 4 1
6 3 5 4 1 2
6 3 5 4 2 1
6 5 4 3 2 1
6 1 5 4 3 2
6 1 5 4 3 2
6 5 4 3 2 1
5 4 3 2 1 6
5 4 3 2 6 1
2 5 4 3 6 1
2 1 5 4 3 6
2 1 5 4 6 3
2 5 4 1 6 3
5 4 1 6 3 2
5 4 6 3 2 1
4 5 6 3 2 1
4 1 5 6 3 2
4 1 5 2 6 3
4 5 2 1 6 3
4 3 5 2 1 6
4 3 5 2 6 1
4 3 2 5 6 1
4 3 2 1 5 6
4 3 2 1 6 5
4 3 2 1 6 5
4 3 1 6 5 2
4 3 6 5 2 1
4 3 6 5 2 1
4 1 3 6 5 2
4 1 3 2 6 5
4 3 2 1 6 5
3 2 1 6 5 4
3 2 6 5 4 1
2 3 6 5 4 1
2 1 3 6 5 4
2 1 6 5 4 3
2 1 6 5 4 3
1 6 5 4 3 2
6 5 4 3 2 1
6 5 4 3 2 1
移動次數:65
此外,需注意C或C++語言函數調用遞迴深度是有限的,且不同編譯器深度不同。