Share my python bfs solution

  • 0

    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):
        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:
                    if newword==endWord: return count+1
                    if newword in wordList:
                        q+=(newword, count+1),
        return 0

Log in to reply

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