-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127.cpp
38 lines (35 loc) · 1.23 KB
/
127.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
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int M = beginWord.size();
// Map intermediate words to their adjudicate words (e.g. d*g -> [dog, dig])
unordered_map<string, unordered_set<string>> mid = {};
for (string word : wordList)
for (int i = 0; i < M; ++i) {
string generic = word;
generic[i] = '*';
mid[generic].insert(word);
}
// BFS on graph
unordered_set<string> visited = {};
queue<string> q;
q.push(beginWord);
int pathLen = 0;
while (!q.empty()) {
++pathLen;
for (int i = q.size(); i > 0; --i) {
string word = q.front(); q.pop();
if (word.compare(endWord) == 0) return pathLen;
visited.insert(word);
for (int i = 0; i < M; ++i) {
string generic = word;
generic[i] = '*';
for (string g: mid[generic])
if (visited.find(g) == visited.end())
q.push(g);
}
}
}
return 0;
}
};