题目
解析
这道题目是接127的一道follow up。127是让你计算最短路径的长度,而这边则要让你大音每条最短路径。这道题目有很多的解法,每个人的思路也不一样,但是为了跟127的解法保持一致性呢,我这边采用一种比较初级的方法:BFS+backtracking。
最初级的版本是这样的,利用BFS求出最短路径,从beginWord开始,正向寻找最短的路径,寻找路径依旧使用之前的搜索方式。这样做会超时,39个test case通过了21个。代码如下:
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
if endWord not in wordList:
return []
def backtracking(curr_step,min_step,path,word):
if curr_step>min_step:
return
if word == endWord and curr_step==min_step:
ans.append(path[:])
for i in range(len(word)):
for nei in neighbors[word[:i]+'*'+word[i+1:]]:
if nei not in visited_path:
#visited_path.add(nei)
path.append(nei)
backtracking(curr_step+1,min_step,path,nei)
path.pop()
#visited_path.remove(nei)
neighbors = collections.defaultdict(list)
for word in wordList:
for i in range(len(word)):
neighbors[word[:i]+'*'+word[i+1:]].append(word)
q = collections.deque()
visited = set()
q.append((beginWord,1))
visited.add(beginWord)
while q:
word,step = q.popleft()
if word==endWord:
#min_step = step
break
for i in range(len(word)):
for nei in neighbors[word[:i]+'*'+word[i+1:]]:
if nei not in visited:
q.append((nei,step+1)