C语言汉诺塔程序

来源:百度知道 编辑:UC知道 时间:2024/04/27 20:08:53
void move( char x, char y )

{
printf( "%c ---> %c\n", x, y );
}

void hanoi( int n, char one, char two, char three )

{
if ( n == 1 ) move( one , three )

else

{
hanoi( n - 1, one , three, two );

move( one, three );

hanoi( n - 1, two, one, three );
}
}
这段程序还是看不懂,当n值为3时就进行判断 n == 1,条件为假接着就执行
else的语句变成 ( 3 - 1, one, three, two )
然后就执行 move( one, three ),由于 one 为'A', three 为'C'.所以
打印出 A----> C
再接着执行( 3 - 1, two, one, three ) two 为 'B', one 为'A',
three为'C',至此第一遍调用就运行完了.剩下的以此类推.
最后每运行move( one, three )就应该打印.
n = 3,就应该打印3次啊.

我看了半天都没看明白,move( one, three )怎么就能输出移动3个盘子的
7个步骤.

N=3时候做
hanoi( 3 - 1, one , three, two ); //展开如下:
//////////////////////////////////hanoi( 2 - 1, one , three, two ); //展开如下:
////////////////////////////////////////////////////////////////////if ( n == 1 ) move( one , three ) ##第一次输出

//////////////////////////////////move( one, three ); ##第二次输出

//////////////////////////////////hanoi( 2 - 1, two, one, three ); //展开如下:
////////////////////////////////////////////////////////////////////if ( n == 1 ) move( one , three ) ##第三次输出

move( one, three ); ##第四次输出

hanoi( 3 - 1, two, one, three );//展开如下:
//////////////////////////////////hanoi( 2 - 1, one , three, two ); //展开如下:
////////////////////////////////////////////////////////////////////if ( n == 1 ) move( one , three ) ##第五次输出

//////////////////////////////////move( one, three ); ##第六次输出

//////////////////////////////////hanoi( 2 - 1, two, one, three );//展开如下:
/////////////////////