-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode127.cpp
42 lines (41 loc) · 1.04 KB
/
leetcode127.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
40
41
42
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
return bfs(beginWord,endWord,wordList);
}
int bfs(string beginWord, string endWord, unordered_set<string> wordList)
{
queue<pair<string,int> > q;
q.push(make_pair(beginWord,1));
unordered_set<string> visited;
visited.insert(beginWord);
bool found = false;
while(!q.empty())
{
pair<string,int> cur = q.front();
q.pop();
string word = cur.first;
int len = word.size();
for (int i = 0; i < len; ++i)
{
string newWord(word);
for(int j = 0; j < 26;++j)
{
newWord[i] = 'a' + j;
if(newWord == endWord)
{
found = true;
return cur.second+1;
}
if(wordList.count(newWord) > 0 && visited.count(newWord) == 0)
{
visited.insert(newWord);
q.push(make_pair(newWord,cur.second+1));
}
}
}
}
if(found == false)
return 0;
}
};