-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWord Ladder.cpp
63 lines (55 loc) · 1.23 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
1
7
poon plee same poie plie poin plea
toon plea
*/
#include<bits/stdc++.h>
using namespace std;
int wordLadder(int);
int main(){
int t, n;
cin >> t;
while(t--){
cin >> n;
cout << wordLadder(n) << endl;
}
return 0;
}
int wordLadder(int n){
unordered_set<string> us;
string start, target;
queue<string> q;
int level = 0;
for(int i = 0; i < n; i++){
string temp;
cin >> temp;
us.insert(temp);
}
cin >> start >> target;
if(us.find(target) == us.end())
return -1;
q.push(start);
while(!q.empty()){
level++;
int size = q.size();
while(size--){
string word = q.front();
q.pop();
for(int i = 0; i < word.length(); i++){
char original_char = word[i];
for(int j = 'a'; j <= 'z'; j++){
word[i] = j;
if(us.find(word) == us.end())
continue;
if(word == target)
return level;
q.push(word);
us.erase(word);
}
word[i] = original_char;
}
}
}
return -1;
}