⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hanota.txt

📁 这个程序的实现可以明确递归方法的使用
💻 TXT
字号:
这个程序的实现可以明确递归方法的使用,理解结构化编程的概念。
 
原理:
移动n个盘子要经历(2的n次方-1)步。具体实现步骤是:1、将A上(n-1)个盘借助于C先移动到B座上;2、将A剩下的一个盘移动到C上;3、将(n-1)个盘从B借助于A移动到C上。
 
程序实现:
----------------------------------
/*hanoi.c*/
 
#include <stdio.h>
 
int count=0;  //定义全局变量count,计算移动的步数
 
//////////////////////////////////////////////////////////
//函数名:move
//功能:打印出x-->y,也就是具体的移动方法,并且计算总的移动步数
//入口参数:x-代表第一个座
//        y-代表第二个座
//////////////////////////////////////////////////////////
void move(char x,char y)
{
        printf("\t%c-->%c\n",x,y);
        count++;
}
 
//////////////////////////////////////////////////////////
//函数名:hanoi
//功能:将n个盘从one座借助于two座,移动到three座
//入口参数:n-代表总的盘数
//        one-代表第一个座
//        two-代表第二个座
//        three-代表第三个座
//////////////////////////////////////////////////////////
voi hanoi(int n,char one,char two,char three)
{
        if(n==1)            //如果只有一个盘,直接从one到three
                move(one,three);
        else {              //如果有多个1个盘
                hanoi(n-1,one,three,two);//第一步:将n-1个盘从one借助three移到two
                move(one,three);//第二步:将第n个盘从one移到three
                hanoi(n-1,two,one,three);//第三步:将n-1个盘从two借助one移到three
        }
}
 
//////////////////////////////////////////////////////////
//函数名:main
//功能:总的控制,打印出移动方案和移动次数
//入口参数:无
//////////////////////////////////////////////////////////
int main()
{
        int m;
        printf("Input the number of disks:");
        scanf("%d",&m);//输入盘的总数
        printf("The step to moving %3d disks:\n\n",m);
        hanoi(m,'A','B','C');//打印出移动方案
        printf("\nThe total times of moving are %d.\n",count);//打印出移动次数
        return(0);
}
----------------------------------
 
程序结果:
----------------------------------
Makefile
 
CC=gcc
hanoi:hanoi.c
        $(CC) $< -o $@
.PHONY:clean
clean:
        rm -f hanoi
 
[armlinux@lqm hanoi]$ ls
hanoi.c  Makefile
[armlinux@lqm hanoi]$ make
gcc hanoi.c -o hanoi
[armlinux@lqm hanoi]$ ls
hanoi  hanoi.c  Makefile
[armlinux@lqm hanoi]$ ./hanoi 
Input the number of disks:3
The step to moving   3 disks:
        A-->C
        A-->B
        C-->B
        A-->C
        B-->A
        B-->C
        A-->C
The total times of moving are 7.
----------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -