Use dictionaries to reduce the complexity of lookups. Using list will time out.
1 classSolution:2 3 defnextwordslist (self, Word, worddict):4Res_list = []5 forIinchRange (len (word)):6 forJinchstring.ascii_lowercase:7New_word =list (word)8 ifJ! =Word[i]:9New_word[i] =JTenNew_word ="'. Join (New_word) One ifNew_wordinchworddict: A res_list.append (New_word) - delWorddict[new_word] - returnres_list the - - defBFS (self, Beginword, Endword, worddict): - #returns an int +Queue = [] -Queue.append ([Beginword, 1]) + whileQueue: AWord, step = queue[0][0], queue[0][1] at queue.pop (0) - ifWord = = Endword:returnStep - #get the next time you change a word, get a list of words -Nextwords =self.nextwordslist (Word, worddict) - forJinchnextwords: -Queue.append ([J, Step+1]) in return0 - defladderlength (self, Beginword, Endword, wordList): to """ + : Type Beginword:str - : Type Endword:str the : Type WORDLIST:LIST[STR] * : Rtype:int $ """Panax Notoginseng ifBeginwordinchWordList:wordList.remove (Beginword) -Worddict = {} the forWinchWORDLIST:WORDDICT[W] = 1 + returnSelf.bfs (Beginword, Endword, worddict)
leetcode--Word Solitaire (Python)