-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathword-ladder.cc
35 lines (34 loc) · 1.06 KB
/
word-ladder.cc
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
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(dict.empty()) return 0;
queue<string> cur, next;
unordered_set<string> visited;
string word;
int step(1);
if(start == end) return step;
cur.push(start);
visited.insert(start);
++step;
while(!cur.empty()) {
word = cur.front(); cur.pop();
for(int i=0; i<word.size(); ++i) {
for(char c='a'; c<='z'; ++c) {
if(c == word[i]) continue;
swap(word[i], c);
if(word == end) return step;
if(visited.find(word) == visited.end() && dict.find(word) != dict.end()) {
visited.insert(word);
next.push(word);
}
swap(word[i], c);
}
}
if(cur.empty()) {
++step;
cur.swap(next);
}
}
return 0;
}
};