forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0126.cpp
More file actions
executable file
·44 lines (41 loc) · 972 Bytes
/
LC0126.cpp
File metadata and controls
executable file
·44 lines (41 loc) · 972 Bytes
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
43
44
/*
Problem Statement: https://leetcode.com/problems/word-ladder-ii/
*/
class Solution {
public:
vector< vector<string> > findLadders(string beginWord, string endWord, vector<string>& wordList) {
string s1, s2;
vector<string> path, added;
queue< vector<string> > q;
vector< vector<string> > paths;
unordered_set<string> words(wordList.begin(), wordList.end());
q.push({beginWord});
while (!q.empty()) {
int size = q.size();
added.clear();
while (size--) {
path = q.front();
q.pop();
if (path.back() == endWord) {
paths.push_back(path);
continue;
}
s1 = s2 = path.back();
for (int i = 0; i < s1.length(); i++)
for (char c = 'a'; c <= 'z'; c++) {
s2[i] = c;
if (words.count(s2)) {
path.push_back(s2);
q.push(path);
path.pop_back();
added.push_back(s2);
}
s2[i] = s1[i];
}
}
for (string& s: added)
words.erase(s);
}
return paths;
}
};