you are offered a list of words and an initial word and a destination word.your task is to change a letter at a time and reach the end word.
when I see this question,BFS suddenly bump upon me.but there are two tricks on BFS.first, you need not to record all paths as states,but to use a set as queue,which contains unique words at this level.second,when find the next word, use the pre for the next word to record its previous words.
the advantages of this way as following:
1.if a word is visited before,it should not be visited this level
2.words at the same level should only be calculated once.
the trick for finding the next word:
1.use string.ascii_lowercase to replace a letter in the word.
2.it helps cut down the time complexity for this process.
the contain time complexity in set is O(1), but if compare every word with another,it calls O(N*m)
from collections import defaultdict
import string
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
self.pre=defaultdict(list)
q={beginWord}
self.pre[beginWord]=[[beginWord]]
def caldiff(a,wl):
ret=[]
for i in range(len(a)):
for c in string.ascii_lowercase:
w=a[:i]+c+a[i+1:]
if w in wl:
self.pre[w]+=[i+[w] for i in self.pre[a]]
ret.append(w)
return ret
while(len(q)):
tmp=[]
wordList=set(wordList)-q
for i in q:
tmp+=caldiff(i,wordList)
q=set(tmp)
if endWord in q:
break
return self.pre[endWord]
from collections import defaultdict
import string
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
wordList=set(wordList)
pw=defaultdict(list)
for w in wordList:
for i in range(len(w)):
pw[w[:i]+'*'+w[i+1:]].append(w)
q=[beginWord]
pre=defaultdict(list)
pre[beginWord]=[[beginWord]]
visited={beginWord}
while(len(q)):
tmp=set()
for w in q:
for i in range(len(w)):
for u in pw[w[:i]+'*'+w[i+1:]]:
if u not in visited:
for j in pre[w]:
pre[u].append(j+[u])
tmp.add(u)
q=tmp
visited.update(tmp)
if endWord in q:
break
return pre[endWord]