6.汉诺塔

Hanoi(汉诺)塔问题:

         古代有一个梵塔,塔内有3个座,A,B,C。开始时A座上有64个盘子,盘子大小不等,大的在下,小的在上,一个老和尚想把这64个盘子从A移到C座,但规定每次只能移动一个盘,且在移动过程中在3个座上都始终保持大盘在下,小盘在上,在移动过程中可以利用B座,编程序输出盘子移动步骤。

分析:

         (1)将A座上的n-1个盘借助C座先移到B座上;

         (2)把A座上的剩下一个盘移到C座上;

         (3)将n-1个盘从B座借助于A座移到C座上;

 代码1:

//汉诺塔 
#include<stdio.h>
void hanoi(int n,char one,char two,char three);
void move(char x,char y);
int main(){
	printf("input the number of diskes:");
	int m;
	scanf("%d",&m);
	printf("The step to move %d diskes:\n",m);
	hanoi(m,'A','B','C');
	return 0;
} 
void hanoi(int n,char one,char two,char three){
	//将n个盘从one座借助two座,移到three座 
	//one起始 two中转 three目标   
	if(n==1){
		move(one,three);
	}else{
		hanoi(n-1,one,three,two);
		move(one,three);
		hanoi(n-1,two,one,three);
	}
}

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

结果:

input the number of diskes:3
The step to move 3 diskes:
A--->C
A--->B
C--->B
A--->C
B--->A
B--->C
A--->C

代码2:

//汉诺塔 
#include<stdio.h>
void hanoi(int n,char one,char two,char three);
int main(){
	printf("input the number of diskes:");
	int m;
	scanf("%d",&m);
	printf("The step to move %d diskes:\n",m);
	hanoi(m,'A','B','C');
	return 0;
} 
void hanoi(int n,char one,char two,char three){
	//将n个盘从one座借助two座,移到three座 
	//one起始 two中转 three目标   
	if(n==1){
		printf("%c-->%c\n",one,three);
	}else{
		hanoi(n-1,one,three,two);
		printf("%c-->%c\n",one,three);
		hanoi(n-1,two,one,three);
	}
}

结果:

input the number of diskes:3
The step to move 3 diskes:
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值