MSSQL数据库 Oracle数据库 Access数据库 MySQL数据库
返回首页
当前位置: 主页 > 数据库 > MSSQL数据库 >

SQL递归游戏

时间:2010-07-29 08:56来源:未知 作者:admin 点击:

5个flash的游戏地址是
http://www.sostart.com/article/view.php/765
此类游戏一般都是通过穷举或者递归之类的方法来求解,对于编成语言来说都比较简单。
这里用SQL语言的CTE递归来玩玩看。我的算法和答案如下:

 


 
/*
    四个字段分别代表 羊,狼,草,人的位置,0表示河左边,1表示河右边。
    每次都必须有人过河,因为动物和植物们都不会划船。
*/
declare @t table (y bit , l bit , c bit , r bit , path varchar (8000 ))
insert into @t select 0 , 0 , 0 , 0 , ''

;with t
as
(
    select * , 0 as cc from @t union all
    select ~ y , l , c , ~ r , path + '人羊' + ltrim (r )+ '→' , cc + 1 from t where cc < 10 and y = r and y & l & c = 0 and path not like '%人羊_→' union all
    select y , ~ l , c , ~ r , path + '人狼' + ltrim (r )+ '→' , cc + 1 from t where cc < 10 and   l = r and y & l & c = 0 and y <> c and path not like '%人狼_→' union all
    select y , l , ~ c , ~ r , path + '人草' + ltrim (r )+ '→' , cc + 1 from t where   cc < 10 and c = r and y & l & c = 0 and y <> l and path not like '%人草_→' union all
    select y , l , c , ~ r , path + '人' + ltrim (r )+ '→' , cc + 1 from t where cc < 10 and   y & l & c = 0 and y <> c and y <> l and path not like '%人_→'
   
)
select REPLACE (REPLACE (path , '0' , '过河' ), '1' , '返回' ) as path from t where y & l & c = 1

/*
人羊过河→人返回→人草过河→人羊返回→人狼过河→人返回→人羊过河→
人羊过河→人返回→人狼过河→人羊返回→人草过河→人返回→人羊过河→
*/

 


(责任编辑:admin)
[返回顶部]
相关文章【广告是网站生存发展的主要来源,请您多多支持!】
顶一下
(1)
100%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名:密码: 验证码:点击我更换图片
推荐内容