importQueueclassSolution(object):defladderLength(self,beginWord,endWord,wordList):""" :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """wordSet=set([])foriteminwordList:wordSet.add(item)# transfer list into setqueue=Queue.Queue()queue.put(beginWord)goal={beginWord:1}char=[chr(i)foriinrange(ord('a'),ord('z')+1)]# character list a~zwhilenotqueue.empty():# BFScur=queue.get()# FIFOifcur==endWord:returngoal[cur]# basewhilecurinwordSet:wordSet.remove(cur)# remove duplicateforiinrange(len(cur)):# tranverse each position of current wordp1=cur[:i]p2=cur[i+1:]forjinchar:word=p1+j+p2ifwordinwordSet:queue.put(word)goal[word]=goal[cur]+1# new item, step + 1wordSet.remove(word)# important! if visited, should not visit again, so delete.return0if__name__=="__main__":answer=Solution()printanswer.ladderLength("hit","cog",["hot","dot","dog","lot","log"])