字符串进化

 给定一个开始字符串,结束字符串,一个字典,开始字符串变为结束字符串。深度优先算法如下:

import  copy
start="hit"
end="cog"
dict=["pit", "pid", "hot","dot","dog","lot","log"]

qu=[]
count=1

def diffoneChar(d,str):
    c = 0
    for i in range( len( end ) ):
        if d[:i] + d[i + 1:] == str[:i] + str[i + 1:]:
            c = c + 1
    return c == 1


def deepSearch(li,d):
    global  count
    tar=li.copy()
    count+=1
    if count > 1800:
        return

    tar.append( d )
    print(len(li) ,li,d)
    if diffoneChar( d, li[-1] ):
        if (d == end):
            print( "OK------------------------", tar)
        qu.append( tar )
        #print( depth, qu )
    for di in dict:
        if (di not in tar):
            deepSearch(tar,di)

def brandSearch(d):
    global  count
    count+=1
    if count > 40:
        return

    for di in dict:
        if (di not in qu):
            if diffoneChar( d, di ):
                qu.append(di)
            print(qu)
    print("oooo*************************************",d)

dict.append(end)
# print(dict[-1:])
deepSearch([start],"")

从打印结果上看,有回溯

下面是广度优先

def bl(li):
    resultp = []
    for c in li:
        for di in dict:
            if (di not in qu):
                if diffoneChar( c, di ):
                    resultp.append( di )
                    qu.append( di )
    print( 2, resultp)
    return  resultp
qu=[]
result1=bl([start])

result=bl(result1)

result2=bl(result)

result3=bl(result2)
result4=bl(result3)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值