|
| 1 | +''' |
| 2 | + 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: |
| 3 | +
|
| 4 | + Only one letter can be changed at a time. |
| 5 | + Each transformed word must exist in the word list. Note that beginWord is not a transformed word. |
| 6 | + Note: |
| 7 | +
|
| 8 | + Return 0 if there is no such transformation sequence. |
| 9 | + All words have the same length. |
| 10 | + All words contain only lowercase alphabetic characters. |
| 11 | + You may assume no duplicates in the word list. |
| 12 | + You may assume beginWord and endWord are non-empty and are not the same. |
| 13 | + Example 1: |
| 14 | +
|
| 15 | + Input: |
| 16 | + beginWord = "hit", |
| 17 | + endWord = "cog", |
| 18 | + wordList = ["hot","dot","dog","lot","log","cog"] |
| 19 | +
|
| 20 | + Output: 5 |
| 21 | +
|
| 22 | + Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", |
| 23 | + return its length 5. |
| 24 | +''' |
| 25 | + |
| 26 | +class Solution(object): |
| 27 | + def ladderLength(self, beginWord, endWord, wordList): |
| 28 | + """ |
| 29 | + :type beginWord: str |
| 30 | + :type endWord: str |
| 31 | + :type wordList: List[str] |
| 32 | + :rtype: int |
| 33 | + """ |
| 34 | + d = {} |
| 35 | + for word in wordList: |
| 36 | + for i in range(len(word)): |
| 37 | + s = word[:i] + "_" + word[i+1:] |
| 38 | + if s in d: |
| 39 | + d[s].append(word) |
| 40 | + else: |
| 41 | + d[s] = [word] |
| 42 | + |
| 43 | + queue, visited = [], set() |
| 44 | + queue.append((beginWord, 1)) |
| 45 | + while queue: |
| 46 | + word, steps = queue.pop(0) |
| 47 | + if word not in visited: |
| 48 | + visited.add(word) |
| 49 | + |
| 50 | + if word == endWord: |
| 51 | + return steps |
| 52 | + else: |
| 53 | + for index in range(len(word)): |
| 54 | + s = word[:index] + "_" + word[index+1:] |
| 55 | + neigh_words = [] |
| 56 | + if s in d: |
| 57 | + neigh_words = d[s] |
| 58 | + |
| 59 | + for neigh in neigh_words: |
| 60 | + if neigh not in visited: |
| 61 | + queue.append((neigh, steps+1)) |
| 62 | + return 0 |
0 commit comments