-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_ladder.cpp
39 lines (38 loc) · 1.19 KB
/
word_ladder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "headers.h"
class Solution {
public:
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return an integer
*/
int ladderLength(string start, string end, unordered_set<string> &dict) {
// write your code here
queue<string> que;
que.push(start);
int dist = 1;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; ++i) {
string word = que.front();
if (word == end)
return dist;
que.pop();
for (int i = 0; i < word.size(); ++i) {
for (char c = 'a'; c < 'z'; ++c) {
if (c != word[i]) {
swap(c, word[i]);
if (dict.find(word) != dict.end()) {
que.push(word);
dict.erase(word);
}
swap(c, word[i]);
}
}
}
}
dist++;
}
}
};