社区
数据结构与算法
帖子详情
汉若塔的非递归算法???
meng_tenboy
2001-07-13 04:06:32
...全文
107
4
打赏
收藏
汉若塔的非递归算法???
复制链接
扫一扫
分享
转发到动态
举报
AI
作业
写回复
配置赞助广告
用AI写文章
4 条
回复
切换为时间正序
请发表友善的回复…
发表回复
打赏红包
meng_tenboy
2001-07-14
打赏
举报
回复
海星,考完了吗?
现在我可以好好的向你请教一番。
anjun
2001-07-13
打赏
举报
回复
哦
不好意思
搞错了
starfish
2001-07-13
打赏
举报
回复
anjun,人家要的是非递归的,不时递归的!
下面才是非递归的代码:
/* Non-recursive solution to Towers of Hanoi */
void main();
#include <stdio.h>
#define width (rings+1)
void main()
{
int rings, last, next, x, z[500], s[3];
printf("how many rings? "); scanf("%d",&rings);
for(x=1; x<=rings; x++) /* put rings on first peg */
z[x]=width-x;
for(x=0; x<=2*width; x+=width) /* set base for each peg */
z[x]=1000;
/* if even number of rings, put first ring on second peg; if odd, on third */
if(rings%2==0)
{
last=1; s[2]=0; s[1]=1;
z[width+1]=z[rings];
}
else
{
last=2; s[1]=0; s[2]=1;
z[2*width+1]=z[rings];
}
printf("from 1 to %d\n",last+1); s[0]=rings-1;
while(s[0]+s[1]) /* while first and second pegs aren't empty */
{
/* next ring to move is smaller of rings on the two pegs not moved onto last */
if(last==0) next=z[width+s[1]]<z[2*width+s[2]]?1:2;
if(last==1) next=z[s[0]]<z[2*width+s[2]]?0:2;
if(last==2) next=z[s[0]]<z[width+s[1]]?0:1;
/* top ring of 'to' peg must be larger and an even 'distance' away */
if((z[next*width+s[next]]>z[last*width+s[last]])||
((z[last*width+s[last]]-z[next*width+s[next]])%2==0)) last=3-next-last;
printf("from %d to %d\n",next+1,last+1);
s[next]=s[next]-1; s[last]=s[last]+1; /* move from 'next' to 'last' peg */
z[last*width+s[last]]=z[next*width+s[next]+1];
}
}
anjun
2001-07-13
打赏
举报
回复
class Hanoi
{
friend void TowersOfHanoi(int);
public:
void TowersOfHanoi(int n,int x,int y,int z);
private:
Stack<int>*S[4];
};
void Hanoi::TowerOfHanoi(int n,int x,int y,int z)
{
int d;
if(n>0)
{
TowersOfHanoi(n-1,x,z,y);
S[x]->Delete(d);
S[y]->Add(d);
ShoeState();
TowerOfHanoi(n-1,z,y,x);
}
}
void TowerOfHanoi(int n)
{
Hanoi X;
X.S[1]=new Stack<int>(n);
X.S[2]=new Stack<int>(n);
X.S[3]=new Stack<int>(n);
for(int d=n;d>0;d--)
X.S[1]->Add(d);
X.TowerOfHanoi(n,1,2,3)
}
汉若塔
的实现,用vc写的程序,有界面
汉若塔
,也被称为汉诺塔游戏或汉诺塔谜题,是一个经典的逻辑思维问题,源自印度古老的传说。在这个游戏中,有三个柱子和一堆大小不一的圆盘,目标是将所有圆盘从第一个柱子移动到第三个柱子,每次只能移动一个圆盘,...
汉诺塔问题:递归与
非递归
实现
非递归
实现(利用堆栈): 1.定义栈类: 2.定义问题栈: 3.主函数: 方式1:利用数组充当堆栈 方式2:利用单向队列充当堆栈:
非递归
代码思路讲解: 1.汉诺塔问题是什么? 相传在古印度圣庙中,有一种被...
汉若塔
游戏
非递归
解法(c#)
汉若塔
游戏
非递归
解法(c#实现)//
汉若塔
游戏
非递归
解法(c#) using System;using System.Collections.Generic;using System.Text;namespace hanruota{ class Program { static void Main(string[] ...
计算机在执行递归
算法
时效率低 为什么,数学与计算机学院23
非递归
算法
的效率分析很常用.PPT...
数学与计算机学院23
非递归
算法
的效率分析很常用2009-2010-2
算法
设计与分析复习提纲 考试时间及地点 18周周5(2010-7-2)10:00-11:50 地点:6B-107?,隔位就座 请各位同学在答题卷左上角写上自己考试序号 例如:序号为9...
汉诺塔(Hanoi)问题归纳总结
汉诺塔问题递归、
非递归
算法
、启发式
算法
解决汉诺塔,双色汉诺塔...
数据结构与算法
33,027
社区成员
35,335
社区内容
发帖
与我相关
我的任务
数据结构与算法
数据结构与算法相关内容讨论专区
复制链接
扫一扫
分享
社区描述
数据结构与算法相关内容讨论专区
社区管理员
加入社区
获取链接或二维码
近7日
近30日
至今
加载中
查看更多榜单
社区公告
暂无公告
试试用AI创作助手写篇文章吧
+ 用AI写文章