|
1 | 1 | class Solution {
|
2 | 2 | public:
|
3 | 3 | int ladderLength(string start, string end, unordered_set<string> &dict) {
|
4 |
| - // Start typing your C/C++ solution below |
5 |
| - // DO NOT write int main() function |
6 |
| - |
7 |
| - queue<pair<string, int>> Q; |
8 |
| - unordered_set<string> visited; |
9 |
| - Q.push(make_pair(start, 1)); |
10 |
| - |
11 |
| - while (!Q.empty()) { |
12 |
| - pair<string, int> src = Q.front(); |
13 |
| - Q.pop(); |
14 |
| - if (src.first == end) { |
15 |
| - return src.second; |
16 |
| - } |
17 |
| - vector<string> neighbor; |
18 |
| - getNeighbors(src.first, neighbor, dict); |
19 |
| - for (string word : neighbor) { |
20 |
| - if (visited.find(word) == visited.end()) { |
21 |
| - visited.insert(word); |
22 |
| - Q.push(make_pair(word, src.second + 1)); |
23 |
| - } |
24 |
| - } |
25 |
| - } |
26 |
| - return 0; |
27 |
| - } |
| 4 | + queue<string> q; |
| 5 | + unordered_map<string, bool> visited; |
| 6 | + map<string, string> steps; |
28 | 7 |
|
29 |
| - void getNeighbors(const string& word, |
30 |
| - vector<string>& neighbor, |
31 |
| - const unordered_set<string>& dict) { |
32 |
| - for (size_t i = 0; i < word.size(); i++) { |
33 |
| - string copyword(word); |
34 |
| - for (char ch = 'a'; ch <= 'z'; ch++) { |
35 |
| - copyword[i] = ch; |
36 |
| - if (dict.find(copyword) != dict.end()) { |
37 |
| - neighbor.push_back(copyword); |
| 8 | + q.push(start); |
| 9 | + visited[start] = true; |
| 10 | + while (!q.empty()) { |
| 11 | + string u = q.front(); |
| 12 | + q.pop(); |
| 13 | + if (u == end) { |
| 14 | + int count = 1; |
| 15 | + while (steps.find(u) != steps.end()) { |
| 16 | + u = steps[u]; |
| 17 | + count++; |
| 18 | + } |
| 19 | + return count; |
| 20 | + } |
| 21 | + string v = u; |
| 22 | + for (int i = 0; i < v.size(); i++) { |
| 23 | + for (char c = 'a'; c <= 'z'; c++) { |
| 24 | + v[i] = c; |
| 25 | + if (visited.find(v) == visited.end() |
| 26 | + && dict.find(v) != dict.end()) { |
| 27 | + visited[v] = true; |
| 28 | + steps[v] = u; |
| 29 | + q.push(v); |
38 | 30 | }
|
39 | 31 | }
|
| 32 | + v[i] = u[i]; |
40 | 33 | }
|
| 34 | + } |
| 35 | + return 0; |
41 | 36 | }
|
42 | 37 | };
|
0 commit comments