SQL递归游戏-你厉害吗,来过5关

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

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

 


/*

    前五个字段分别代表 左人数,左鬼数,右人数,右鬼数,船位置
    船位置为代表在右边,代表在左边
    当右边没有人和鬼时(gr+pr>0),不执行返回操作,递归结束
*/
; with t ( pl , gl , pr , gr , boat , path )
as
(
    select 0 , 0 , 3 , 3 , cast ( 0 as bit ), cast ( '' as varchar ( 8000 )) union all
    select pl + 2 as pl , gl , pr - 2 as pr , gr , ~ boat , path + '2人过河→'
        from t where boat = 0 and pr >= 2 and ( pr - 2 >= gr or pr = 2 ) union all
    select pl + 1 , gl + 1 , pr - 1 , gr - 1 , ~ boat , path + '1人鬼过河→'
        from t where boat = 0 and pr >= 1 and gr >= 1 and pl >= gl   union all
    select pl , gl + 2 , pr , gr - 2 , ~ boat , path + '2鬼过河→'
        from t where boat = 0 and gr >= 2 and ( pl - 2 >= gl or pl = 0 )
  • 1
    点赞
  • 207
    收藏
    觉得还不错? 一键收藏
  • 112
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 112
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值