给定一个开始字符串,结束字符串,一个字典,开始字符串变为结束字符串。深度优先算法如下:
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)