趁有人霸占电脑的时间,把汉诺塔问题简单的实现了一下,呵呵。反正以前没实现过,没想很简单。可能书上的实现更简单吧。
没看,呵呵。主要是定义一个hanot函数,包括4个参数,hanot(A,C,B,N)表示把A上的N个元素借助B放到C上。
虽然是入门级问题,可还是有人不明白,所以索性把代码贴了出来,运行下就明白了吧,典型的递归问题。
代码如下:
-----------------------------------------------------------------------------------------
1 #include<stdio.h>
2
3 void hanot(char from,char to,char tmp,int N)
4 {
5 if(N == 1)
6 printf("%c -> %c /n",from,to);
7 else
8 {
9 /*first move N-1 elemnts of A to B by C*/
10 hanot(from,tmp,to,N-1);
11 /*move directly the Nth element of A to C*/
12 hanot(from,to,tmp,1);
13 /*move N-1 elements of B to C by A*/
14 hanot(tmp,to,from,N-1); }
15 }
16
17 int main(void)
18 {
19 char A,B,C;
20 int N;
21 A = 'A';
22 B = 'B';
23 C = 'C';
24 printf("Input N:/n");
25 scanf("%d",&N);
26
27 hanot(A,C,B,N);
28 }
-----------------------------------------------------------------------------------------