Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2d4d173

Browse files
committed
"Word Ladder"
1 parent 987e9ff commit 2d4d173

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
173173
| 130 | [Surrounded Regions] | |
174174
| 129 | [Sum Root to Leaf Numbers] | [C](src/129.c) |
175175
| 128 | [Longest Consecutive Sequence] | [C](src/128.c) |
176-
| 127 | [Word Ladder] | |
176+
| 127 | [Word Ladder] | [C++](src/127.cpp) |
177177
| 126 | [Word Ladder II] | |
178178
| 125 | [Valid Palindrome] | [C](src/125.c) |
179179
| 124 | [Binary Tree Maximum Path Sum] | |

‎src/127.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <queue>
4+
#include <map>
5+
#include <unordered_set>
6+
#include <cassert>
7+
8+
using namespace std;
9+
10+
class Solution {
11+
public:
12+
int ladderLength(string beginWord, string endWord, unordered_set<string> &wordList) {
13+
queue<string> q;
14+
map<string, bool> visited;
15+
q.push(beginWord);
16+
q.push("LEVEL_END_TAG");
17+
visited[beginWord] = true;
18+
int level = 1;
19+
while (!q.empty()) {
20+
string word = q.front();
21+
q.pop();
22+
if (word != "LEVEL_END_TAG") {
23+
for (int i = 0; i < word.length(); i++) {
24+
string new_word = word;
25+
for (int j = 0; j < 26; j++) {
26+
new_word[i] = j + 'a';
27+
28+
if (new_word == endWord) {
29+
level++;
30+
return level;
31+
}
32+
33+
auto it = wordList.find(new_word);
34+
if (it != wordList.end() && !visited[new_word]) {
35+
q.push(new_word);
36+
visited[new_word] = true;
37+
}
38+
}
39+
}
40+
}
41+
else {
42+
level++;
43+
if (!q.empty()) {
44+
q.push("LEVEL_END_TAG");
45+
}
46+
}
47+
}
48+
49+
return 0;
50+
}
51+
};
52+
53+
int main() {
54+
unordered_set<string> wordList0 = { "hot", "dot", "dog", "lot", "log" };
55+
unordered_set<string> wordList1 = { "hot", "dog" } ;
56+
57+
Solution s;
58+
assert(s.ladderLength("hit", "cog", wordList0) == 5);
59+
assert(s.ladderLength("hot", "dog", wordList1) == 0);
60+
61+
printf("all tests passed!\n");
62+
63+
return 0;
64+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /