Leetcode 每日一题
题目链接: 127. 单词接龙
难度:中等
解题思路: 这道题很明显是一道搜索问题,可以用BFS来求解,但是注意裸BFS会超时,生成的解空间会很大。所以需要对用双向BFS求解。其中两个队列分别存储从beginWord和endWord开始的解。如果他们找到了同一个值,那么就找到答案了。
如图所示,蓝色为正向解空间,红色为反向解空间,中间的交集为使用双向BFS的解空间,可以发现这个解空间比单向的时候会小很多。
题解:
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
lenl = len(wordList)
lenw = len(beginWord)
# 定义双向队列
queue1 = []
queue2 = []
# 打标记
visit1 = [0] * (lenl)
visit2 = [0] * (lenl)
# 记录步数
dist1 = [0] * (lenl)
dist2 = [0] * (lenl)
# 双向bfs
def bfs():
queue1.append([beginWord, 1])
queue2.append([endWord, 1])
if beginWord in wordList:
visit1[wordList.index(beginWord)] = 1
visit2[wordList.index(endWord)] = 1
while len(queue1) != 0 or len(queue2) != 0:
# 正向bfs
lenq1 = len(queue1)
for step in range(lenq1):
node1 = queue1.pop(0)
for j in range(lenl):
# 前后向都找到了
if visit1[j] + visit2[j] == 2:
return dist1[j] + dist2[j] + 1
if visit1[j] != 0:
continue
example = wordList[j]
dist1[j] = node1[1]
cnt = 0
for i in range(lenw):
if node1[0][i] == example[i]:
cnt += 1
# print(cnt)
if cnt == lenw - 1:
queue1.append([example, node1[1] + 1])
visit1[j] = 1
# 反向bfs
lenq2 = len(queue2)
for step in range(lenq2):
node2 = queue2.pop(0)
for j in reversed(range(lenl)):
# 前后向都找到了
if visit1[j] + visit2[j] == 2:
return dist1[j] + dist2[j] + 1
if visit2[j] != 0:
continue
example = wordList[j]
dist2[j] = node2[1]
cnt = 0
for i in range(lenw):
if node2[0][i] == example[i]:
cnt += 1
if cnt == lenw - 1:
queue2.append([example, node2[1] + 1])
visit2[j] = 1
# print(node1, node2)
return 0
res = bfs()
# print(res)
return res