|
| 1 | +--- |
| 2 | +title: Leetcode 127. Word Ladder |
| 3 | +description: Explanation for Leetcode 127 - Word Ladder, and its solution in Python. |
| 4 | +date: 2025-04-29 |
| 5 | +categories: [Leetcode, Graphs, Hard] |
| 6 | +tags: [Leetcode, Python, Study, Graphs, Hard] |
| 7 | +math: true |
| 8 | +--- |
| 9 | + |
| 10 | +## Problem |
| 11 | +[Leetcode 127 - Word Ladder](https://leetcode.com/problems/word-ladder/description/) |
| 12 | + |
| 13 | +Example: |
| 14 | +``` |
| 15 | +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] |
| 16 | +Output: 5 |
| 17 | +Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. |
| 18 | +
|
| 19 | +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] |
| 20 | +Output: 0 |
| 21 | +Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. |
| 22 | +``` |
| 23 | + |
| 24 | +## Approach |
| 25 | + |
| 26 | +We can use BFS to find the words that have similar words in wordList. Once we find the correct word, we can return the counts that we've searched through |
| 27 | + |
| 28 | +Here is the Python code for the solution: |
| 29 | +```python |
| 30 | +class Solution: |
| 31 | + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: |
| 32 | + if beginWord == endWord or endWord not in wordList: |
| 33 | + return 0 |
| 34 | + |
| 35 | + words, res = set(wordList), 0 |
| 36 | + q = deque([beginWord]) |
| 37 | + while q: |
| 38 | + res += 1 |
| 39 | + for _ in range(len(q)): |
| 40 | + node = q.popleft() |
| 41 | + if node == endWord: |
| 42 | + return res |
| 43 | + for i in range(len(node)): |
| 44 | + for c in range(97, 123): |
| 45 | + if chr(c) == node[i]: |
| 46 | + continue |
| 47 | + nei = node[:i] + chr(c) + node[i+1:] |
| 48 | + if nei in words: |
| 49 | + q.append(nei) |
| 50 | + words.remove(nei) |
| 51 | + |
| 52 | + return 0 |
| 53 | +``` |
| 54 | +## Time Complexity and Space Complexity |
| 55 | + |
| 56 | +Time Complexity: $O(m^2 * n)$ |
| 57 | + |
| 58 | +Space Complexity: $O(m^2 * n)$ |
0 commit comments