127.Word Ladder

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

Given:
beginWord="hit",endWord="cog",wordList=["hot","dot","dog","lot","log","cog"]

As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Method 1 BFS + alphabic character check(26^n time, n space)

  • Since only one character can be changed, we can go through all alphabetical characters for every index in our beginWord string and find out if they exist in wordList (convert to set).
  • Then since we want the shortest transformation, we can use BFS instead of DFS to traverse the possibilties of all the words that can be transformed from the previous word, and increment a counter along the way.
  • In order to prevent cycle, we remove each word from wordList every time we complete a search of all characters combos of that word.
  • Return the counter once we found endWord.
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        wordList = set(wordList)
        queue = [beginWord]
        count = 1
        word_len = len(beginWord)
        while queue:
            count += 1
            new_q = []
            for word in queue:
                for i in xrange(word_len):
                    for c in 'abcdefghijklmnopqrstuvwxyz':
                        next_word = word[:i] + c + word[i+1:]
                        if next_word in wordList:
                            if next_word == endWord:
                                return count
                            new_q.append(next_word)
                            wordList.remove(next_word)
            queue = new_q
        return 0

results matching ""

    No results matching ""