-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Ladder_II.cpp
More file actions
105 lines (94 loc) · 2.63 KB
/
Word_Ladder_II.cpp
File metadata and controls
105 lines (94 loc) · 2.63 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution {
public:
vector<vector<string>> findSequences(string beginWord, string endWord, vector<string>& wordList) {
// code here
unordered_set<string> st(wordList.begin(), wordList.end());
queue<vector<string>>q;
q.push({beginWord});
vector<string> usedOnLevel;
usedOnLevel.push_back(beginWord);
vector<vector<string>> ans;
int level = 0;
while(!q.empty())
{
vector<string> vec = q.front();
q.pop();
if(vec.size() > level)
{
level++;
for(auto it : usedOnLevel)
st.erase(it);
usedOnLevel.clear();
}
string word = vec.back();
if(word == endWord)
{
if(ans.size() == 0)
ans.push_back(vec);
else if(ans[0].size() == vec.size())
ans.push_back(vec);
}
for(int i = 0; i < word.size(); i++)
{
char OriginalChar = word[i];
for(char ch = 'a'; ch <= 'z'; ch++)
{
word[i] = ch;
if(st.count(word) > 0){
vec.push_back(word);
q.push(vec);
vec.pop_back();
usedOnLevel.push_back(word);
}
}
word[i] = OriginalChar;
}
}
return ans;
}
};
//{ Driver Code Starts.
bool comp(vector<string> a, vector<string> b)
{
string x = "", y = "";
for(string i: a)
x += i;
for(string i: b)
y += i;
return x<y;
}
int main(){
int tc;
cin >> tc;
while(tc--){
int n;
cin >> n;
vector<string>wordList(n);
for(int i = 0; i < n; i++)cin >> wordList[i];
string startWord, targetWord;
cin >> startWord >> targetWord;
Solution obj;
vector<vector<string>> ans = obj.findSequences(startWord, targetWord, wordList);
if(ans.size()==0)
cout<<-1<<endl;
else
{
sort(ans.begin(), ans.end(), comp);
for(int i=0; i<ans.size(); i++)
{
for(int j=0; j<ans[i].size(); j++)
{
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
}
}
return 0;
}
// } Driver Code Ends