-
Notifications
You must be signed in to change notification settings - Fork 2
/
127.Word Ladder.cpp
39 lines (34 loc) · 1.15 KB
/
127.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
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> u_set(wordList.begin(), wordList.end());
int res = ladderLengthHelper(beginWord, endWord, u_set);
return res;
}
int ladderLengthHelper(string start, string end, unordered_set<string> &dict) {
if (dict.find(end) == dict.end()) return 0;
queue<pair<string,int> >q;
unordered_set<string> visited;
q.push(make_pair(start,1));
visited.insert(start);
//开始判断
while(!q.empty()){
string curStr=q.front().first;
int curStep=q.front().second;
q.pop();
for(int i=0;i<curStr.size();i++){
string tmp=curStr;
for(int j=0;j<26;j++){
tmp[i] = j+'a';
if(tmp==end) return curStep+1;
if(visited.find(tmp)==visited.end()&&dict.find(tmp)!=dict.end()){
//为了避免"hot" "dog" ["hot","dog"] 这种情况下,程序不动,一直在运行
visited.insert(tmp);
q.push(make_pair(tmp,curStep+1));
}
}
}
}
return 0;
}
};