递归实现汉诺塔

来源:互联网 发布:模拟退火算法c代码 编辑:程序博客网 时间:2024/06/06 14:03

解决思想:若A塔上有n个盘子,则先将上层n-1个盘子移动到B塔上,最底层的盘子移动到C塔上,再将B塔上的n-1个盘子移动到C塔上。

#include <stdio.h>void move(int count, int start, int finish, int temp){    if (count > 0)    {        move(count - 1, start, temp, finish);    // 将上层的n-1个盘子移动到temp塔(B塔)上        printf("Move disk %d from %d to %d.\n", count, start, finish);        move(count - 1, temp, finish, start);    // 将temp塔上的n-1个盘子移动到finish塔(C塔)上    }}int main(void){    int n;    scanf(" %d", &n);    move(n, 1, 3, 2);    return 0;}


1 0
原创粉丝点击