|
| 1 | +""" |
| 2 | +Given two words (beginWord and endWord), and a dictionary's word list, |
| 3 | +find the length of shortest transformation sequence |
| 4 | +from beginWord to endWord, such that: |
| 5 | +
|
| 6 | +Only one letter can be changed at a time |
| 7 | +Each intermediate word must exist in the word list |
| 8 | +For example, |
| 9 | +
|
| 10 | +Given: |
| 11 | +beginWord = "hit" |
| 12 | +endWord = "cog" |
| 13 | +wordList = ["hot","dot","dog","lot","log"] |
| 14 | +As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", |
| 15 | +return its length 5. |
| 16 | +. |
| 17 | +Note: |
| 18 | +Return 0 if there is no such transformation sequence. |
| 19 | +All words have the same length. |
| 20 | +All words contain only lowercase alphabetic characters. |
| 21 | +""" |
| 22 | +def ladderLength(beginWord, endWord, wordList): |
| 23 | + """ |
| 24 | + Bidirectional BFS!!! |
| 25 | + :type beginWord: str |
| 26 | + :type endWord: str |
| 27 | + :type wordList: Set[str] |
| 28 | + :rtype: int |
| 29 | + """ |
| 30 | + beginSet = set() |
| 31 | + endSet = set() |
| 32 | + beginSet.add(beginWord) |
| 33 | + endSet.add(endWord) |
| 34 | + result = 2 |
| 35 | + while len(beginSet) != 0 and len(endSet) != 0: |
| 36 | + if len(beginSet) > len(endSet): |
| 37 | + beginSet, endSet = endSet, beginSet |
| 38 | + nextBeginSet = set() |
| 39 | + for word in beginSet: |
| 40 | + for ladderWord in wordRange(word): |
| 41 | + if ladderWord in endSet: |
| 42 | + return result |
| 43 | + if ladderWord in wordList: |
| 44 | + nextBeginSet.add(ladderWord) |
| 45 | + wordList.remove(ladderWord) |
| 46 | + beginSet = nextBeginSet |
| 47 | + result += 1 |
| 48 | + print(beginSet) |
| 49 | + print(result) |
| 50 | + return 0 |
| 51 | + |
| 52 | +def wordRange(word): |
| 53 | + for ind in range(len(word)): |
| 54 | + tempC = word[ind] |
| 55 | + for c in [chr(x) for x in range(ord('a'), ord('z')+1)]: |
| 56 | + if c != tempC: |
| 57 | + yield word[:ind] + c + word[ind+1:] |
| 58 | + |
| 59 | +beginWord = "hit" |
| 60 | +endWord = "cog" |
| 61 | +wordList = ["hot","dot","dog","lot","log"] |
| 62 | +print(ladderLength(beginWord, endWord, wordList)) |
0 commit comments