字符串進化

 給定一個開始字符串,結束字符串,一個字典,開始字符串變爲結束字符串。深度優先算法如下:

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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章