Redian新闻
>
双向bfs果然有效率,pyhon 664ms 过wordladder I
avatar
双向bfs果然有效率,pyhon 664ms 过wordladder I# JobHunting - 待字闺中
p*e
1
就是代码丑了一些,重复部分好多。
avatar
j*3
2
上代码
avatar
p*e
3
代码很难看,晚上有时间再修改。 同样单向bfs需要1200ms左右ac。
class Solution:

def ladderLength(self, start, end, dict):
dict.add(end)

current, distance, visited = [start], 1, {start:0}
bcurrent, bdistance, bvisited = [end], 1, {end:0}
while current and bcurrent:
pre, bpre,next, bnext = [], [], [], []
for word in current:
for i in xrange(len(word)):
left, right = word[:i], word[i + 1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
candidate = left + j + right
if candidate in dict and candidate not in visited:
visited[candidate] = 0
next.append(candidate)
for word in next:
if word in bpre:
return distance + bdistance - 1
if word in bcurrent:
return distance + bdistance
pre, current, distance = current, next, distance + 1


for word in bcurrent:
for i in xrange(len(word)):
left, right = word[:i], word[i + 1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
candidate = left + j + right
if candidate in dict and candidate not in bvisited:
bvisited[candidate] = 0
bnext.append(candidate)
for word in bnext:
if word in pre:
return distance + bdistance - 1
if word in current:
return distance + bdistance
bpre, bcurrent, bdistance = bcurrent, bnext, bdistance + 1
return 0


【在 j**********3 的大作中提到】
: 上代码
avatar
l*r
4
Mark!
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。