Skip to content

Commit 1071c14

Browse files
committed
127-word-ladder.md Added Python solution.
1 parent e53888e commit 1071c14

File tree

9 files changed

+176
-9
lines changed

9 files changed

+176
-9
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
temp/
33
solutions/empty-template.md
44
solutions/empty-template-with-images.md
5+
/solutions/leetcode-solution-common.md

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,5 +68,6 @@ You can skip the more difficult problems and do them later.
6868
- [200. Number of Islands](solutions/1-1000/200-number-of-islands.md) was solved in _Python, Java, C++, JavaScript, C#, Go, Ruby_ and **3** solutions.
6969
- [695. Max Area of Island](solutions/1-1000/695-max-area-of-island.md) was solved in _Python, Java, C++, JavaScript, C#, Go, Ruby_.
7070
- [827. Making A Large Island](solutions/1-1000/827-making-a-large-island.md) was solved in _Python_.
71+
- [127. Word Ladder](solutions/1-1000/127-word-ladder.md) was solved in _Python_.
7172

7273
More LeetCode problems will be added soon...

images/127.png

32.7 KB
Loading
File renamed without changes.
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
# LeetCode 127. Word Ladder's Solution
2+
LeetCode problem link: [127. Word Ladder](https://leetcode.com/problems/word-ladder/)
3+
4+
## LeetCode problem description
5+
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
6+
7+
* Every adjacent pair of words differs by a single letter.
8+
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
9+
* `sk == endWord`
10+
11+
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return **the number of words** in the **shortest transformation sequence** from `beginWord` to `endWord`, or `0` if no such sequence exists.
12+
13+
### Example 1
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+
20+
### Example 2
21+
```
22+
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
23+
Output: 0
24+
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
25+
```
26+
27+
### Constraints
28+
- `1 <= beginWord.length <= 10`
29+
- `endWord.length == beginWord.length`
30+
- `1 <= wordList.length <= 5000`
31+
- `wordList[i].length == beginWord.length`
32+
- `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
33+
- `beginWord != endWord`
34+
- All the words in `wordList` are **unique**.
35+
36+
## Intuition
37+
This problem is hard. Before solving this problem, you can do the following problem first:
38+
39+
- [200. Number of Islands (Solution 3: Breadth-First Search)](200-number-of-islands-3.md)
40+
41+
The **word transformation sequence** problem can be abstracted into a **graph theory** problem. And it is an **undirected graph**:
42+
43+
![](../../images/127.png)
44+
45+
### Breadth-First Search
46+
![](../../images/binary_tree_BFS_1.gif)
47+
48+
* As shown in the figure above, **breadth-first search** can be thought of as visiting nodes in rounds and rounds. Actually, whenever you see a question is about
49+
getting `shortest` or `least` of something of a graph, `breadth-first search` would probably help.
50+
51+
* `breadth-first search` emphasizes first-in-first-out, so a **queue** is needed.
52+
53+
## Approach
54+
1. `Breadth-First Search` a graph means traversing **from near to far**, from `circle 1` to `circle N`. Each `circle` is a round of iteration, but we can simplify it by using just 1 round.
55+
1. So through `Breadth-First Search`, when a word matches `endWord`, the game is over, and we can return the number of **circle** as a result.
56+
57+
## Complexity
58+
* Time: `O(n * n)`.
59+
* Space: `O(n * n)`.
60+
61+
## Python
62+
```python
63+
class Solution:
64+
def __init__(self):
65+
self.word_set = None
66+
self.endWord = None
67+
self.queue = deque()
68+
69+
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
70+
self.endWord = endWord
71+
self.word_set = set(wordList)
72+
73+
if endWord not in self.word_set:
74+
return 0
75+
76+
self.queue.append((beginWord, 1))
77+
78+
return self.breadth_first_search()
79+
80+
def breadth_first_search(self):
81+
while self.queue:
82+
word0, circle = self.queue.popleft()
83+
removed_words = set()
84+
85+
for word in self.word_set:
86+
if one_char_different(word, word0):
87+
if word == self.endWord:
88+
return circle + 1
89+
90+
self.queue.append((word, circle + 1))
91+
92+
removed_words.add(word)
93+
94+
self.word_set -= removed_words
95+
96+
return 0
97+
98+
99+
def one_char_different(word1, word2):
100+
different_char_count = 0
101+
102+
for i in range(len(word1)):
103+
if word1[i] != word2[i]:
104+
different_char_count += 1
105+
if different_char_count > 1:
106+
return False
107+
108+
return True
109+
```
110+
111+
## Java
112+
```java
113+
// Welcome to create a PR to complete the code of this language, thanks!
114+
```
115+
116+
## C++
117+
```cpp
118+
// Welcome to create a PR to complete the code of this language, thanks!
119+
```
120+
121+
## JavaScript
122+
```javascript
123+
// Welcome to create a PR to complete the code of this language, thanks!
124+
```
125+
126+
## C#
127+
```c#
128+
// Welcome to create a PR to complete the code of this language, thanks!
129+
```
130+
131+
## Go
132+
```go
133+
// Welcome to create a PR to complete the code of this language, thanks!
134+
```
135+
136+
## Ruby
137+
```ruby
138+
# Welcome to create a PR to complete the code of this language, thanks!
139+
```
140+
141+
## C
142+
```c
143+
// Welcome to create a PR to complete the code of this language, thanks!
144+
```
145+
146+
## Kotlin
147+
```kotlin
148+
// Welcome to create a PR to complete the code of this language, thanks!
149+
```
150+
151+
## Swift
152+
```swift
153+
// Welcome to create a PR to complete the code of this language, thanks!
154+
```
155+
156+
## Rust
157+
```rust
158+
// Welcome to create a PR to complete the code of this language, thanks!
159+
```
160+
161+
## Other languages
162+
```
163+
// Welcome to create a PR to complete the code of this language, thanks!
164+
```

solutions/1-1000/200-number-of-islands-3.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ Please click [Depth-First Search by Iteration Solution](200-number-of-islands-2.
6666
![](../../images/binary_tree_BFS_1.gif)
6767

6868
As shown in the figure above, **breadth-first search** can be thought of as visiting nodes in rounds and rounds.
69+
6970
It emphasizes first-in-first-out, so a **queue** is needed.
7071

7172
## Complexity

solutions/1-1000/42-trapping-rain-water-2.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ This solution will follow **Monotonic Stack**'s common rule: **only calculating
3333

3434
This common rule can be applied to calculating result for **most** of the **Monotonic Stack** problems.
3535

36-
![](../../images/0042.png)
36+
![](../../images/42.png)
3737

3838
### Solution 1
3939
Please click [42. Trapping Rain Water (solution 1)](42-trapping-rain-water.md) to see it.
@@ -97,7 +97,7 @@ class Solution:
9797
return result
9898
```
9999

100-
![](../../images/0042.png)
100+
![](../../images/42.png)
101101

102102
## C++
103103
```cpp
@@ -161,7 +161,7 @@ var trap = function (heights) {
161161
};
162162
```
163163

164-
![](../../images/0042.png)
164+
![](../../images/42.png)
165165

166166
## C#
167167
```c#
@@ -228,7 +228,7 @@ func trap(heights []int) int {
228228
}
229229
```
230230

231-
![](../../images/0042.png)
231+
![](../../images/42.png)
232232

233233
## Ruby
234234
```ruby

solutions/1-1000/42-trapping-rain-water.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ This problem can be solved using **Monotonic Stack**.
3636
1) The right side (current item) is **no shorter** than the left side (the top of stack).
3737
2) The right side (current item) is **shorter** than the left side (the top of stack).
3838

39-
![](../../images/0042.png)
39+
![](../../images/42.png)
4040

4141
Detailed solutions will be given later, and now only the best practices in 7 languages are given.
4242

@@ -108,7 +108,7 @@ class Solution:
108108
return result
109109
```
110110

111-
![](../../images/0042.png)
111+
![](../../images/42.png)
112112

113113
## C++
114114
```cpp
@@ -174,7 +174,7 @@ var trap = function (heights) {
174174
};
175175
```
176176

177-
![](../../images/0042.png)
177+
![](../../images/42.png)
178178

179179
## C#
180180
```c#
@@ -246,7 +246,7 @@ func trap(heights []int) int {
246246
}
247247
```
248248

249-
![](../../images/0042.png)
249+
![](../../images/42.png)
250250

251251
## Ruby
252252
```ruby

solutions/1-1000/827-making-a-large-island.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ Explanation: Can't change any 0 to 1, only one island with area = 4.
3535
- `grid[i][j]` is either `0` or `1`.
3636

3737
## Intuition
38-
This problem is hard. Before solving this problem, you can do the following two problems first.
38+
This problem is hard. Before solving this problem, you can do the following two problems first:
3939

4040
- [200. Number of Islands](200-number-of-islands.md)
4141
- [695. Max Area of Island](695-max-area-of-island.md)

0 commit comments

Comments
 (0)