Share my python bfs solution


  • 0
    F

    Since we dont know if the begin word exists in the wordlist, we need to add this as the begin node to the wordlist set, and remove it means we started from this node.

    class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        wordList.add(beginWord)
        wordList.remove(beginWord)
        lst, q=[chr(i) for i in xrange(97, 123)], [(beginWord,1)]
        while q:
            cur, count=q.pop(0)
            for i in xrange(len(cur)):
                for j in lst:
                    newword=cur[:i]+j+cur[i+1:]
                    if newword==endWord: return count+1
                    if newword in wordList:
                        q+=(newword, count+1),
                        wordList.remove(newword)
        return 0

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.