Demo: How does the Hanoi Tower run ?, Demohanoi
The Hanoi problem is solved by moving the disc on the column recursively. But how does the disk on each column change?
The following program demonstrates the effect for programmers to understand.
# 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 ("number of moves: % d \ n", movecnt); return 0 ;}
Program running result:
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
Number of moves: 65
In addition, it should be noted that the recursive depth of function calls in C or C ++ languages is limited, and the depth of different compilers varies.