用C语言实现汉诺塔的程序
2006-03-05 14:35
357 查看
/*
本程序是模拟汉诺塔的操作过程,
将每一步的执行方法打印出来,
并记录执行次数;
主程序采用递归方式;
每执行一步等待0.5秒;
*/
#include<stdio.h>
#include<conio.h> /*for the function: clrscr()*/
#include<dos.h> /*for the function: delay(int ms) */
int count = 0; /*move times*/
/*将盘从柱子A移动到柱子B*/
void move(char A,char B)
{
delay(500); /*wait 0.5s */
printf("/n%d: %c -> %c",++count,A,B);
}
/*汉诺塔主过程*/
void hanoi(int n,char A,char B,char C)
{
if(n < 1)
return;
if(n == 1)
{
move(A,C);
return;
}
hanoi(n-1,A,C,B);
move(A,C);
hanoi(n-1,B,A,C);
}
int main()
{
int n = 0; /*盘子个数*/
clrscr(); /*clear the screen*/
printf("Please input a int:");
scanf("%d",&n);
/*主过程*/
hanoi(n,'A','B','C');
/*任意键退出*/
printf("/nPress any key to EXIT!");
return getch(); /*wait to get a char*/
}
本程序是模拟汉诺塔的操作过程,
将每一步的执行方法打印出来,
并记录执行次数;
主程序采用递归方式;
每执行一步等待0.5秒;
*/
#include<stdio.h>
#include<conio.h> /*for the function: clrscr()*/
#include<dos.h> /*for the function: delay(int ms) */
int count = 0; /*move times*/
/*将盘从柱子A移动到柱子B*/
void move(char A,char B)
{
delay(500); /*wait 0.5s */
printf("/n%d: %c -> %c",++count,A,B);
}
/*汉诺塔主过程*/
void hanoi(int n,char A,char B,char C)
{
if(n < 1)
return;
if(n == 1)
{
move(A,C);
return;
}
hanoi(n-1,A,C,B);
move(A,C);
hanoi(n-1,B,A,C);
}
int main()
{
int n = 0; /*盘子个数*/
clrscr(); /*clear the screen*/
printf("Please input a int:");
scanf("%d",&n);
/*主过程*/
hanoi(n,'A','B','C');
/*任意键退出*/
printf("/nPress any key to EXIT!");
return getch(); /*wait to get a char*/
}
相关文章推荐
- 用C语言实现汉诺塔的程序
- 利用多线程实现linux下C语言的聊天室程序:
- linux网络编程:用C语言实现的聊天程序(同步通信)
- C语言二进制文件读写程序实现(基础)
- C语言实现的一个万年历小程序
- 程序实现分析C语言的声明语句含义
- C语言实现http get请求程序
- linux网络编程:用C语言实现的聊天程序(异步通信)
- C语言实现的一个简单的HTTP程序
- C语言编写程序,实现多个非负整数四则运算的功能
- 基于C语言实现的Ping程序
- C语言-将1到9这九个数字分成三个3位数,要求第一个3位数,正好是第二个3位数的1/2,是第三个3位数的1/3。问应当怎样分,编写程序实现。
- C语言中的可变参数函数的浅析(以Arm 程序中的printf()函数实现为例)
- C语言链表实现——无限录入单词程序
- 汉诺塔的C语言实现以及冒泡排序
- 递归函数的练习,汉诺塔问题的程序实现(递归)
- 一个简单c语言windows程序的实现
- 基于C语言实现的Ping程序
- C语言趣味程序百例精解之JAVA实现(56)区分旅客国籍
- C语言二进制文件读写程序实现(基础)