-
Notifications
You must be signed in to change notification settings - Fork 0
/
126-Word Ladder II (Bi-Directional BFS).cpp
101 lines (101 loc) · 3.25 KB
/
126-Word Ladder II (Bi-Directional BFS).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
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
class Solution {
public:
struct node
{
string word;
node* parent;
node(string w,node* p=NULL): word(w),parent(p){}
};
int num_swaps=0;
vector<string> temp_res;
vector<vector<string>> result;
void sequential(node* start)
{
if(start)
{
sequential(start->parent);
temp_res.push_back(start->word);
}
}
void add(node* start,node* end) //oderly print
{
temp_res.clear();
if(num_swaps&1)
{
sequential(end);
while(start)
{
temp_res.push_back(start->word);
start=start->parent;
}
}
else
{
sequential(start);
while(end)
{
temp_res.push_back(end->word);
end=end->parent;
}
}
result.push_back(temp_res);
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList)
{
unordered_set<string> dict;
unordered_multimap<string,node*> front,back,temp;
unordered_multimap<string,node*>::const_iterator it,it2;
pair<unordered_multimap<string,node*>::const_iterator,unordered_multimap<string,node*>::const_iterator> range;
bool completed=false;
char letter;
string word;
dict.reserve(wordList.size());
for(string &i:wordList)
dict.insert(i);
if(dict.find(endWord)==dict.end())
return result;
front.insert(pair<string,node*>(beginWord,new node(beginWord)));
back.insert(pair<string,node*>(endWord,new node(endWord)));
dict.erase(beginWord);
dict.erase(endWord);
while(!front.empty()&&!back.empty())
{
temp.clear();
if(back.size()<front.size())
{
num_swaps++; //required for oderly print
front.swap(back);
}
for(it=front.begin();it!=front.end();it++)
{
word=it->first;
for(int i=0;i<word.length();i++)
{
letter=word[i];
for(int j=0;j<26;j++)
{
word[i]='a'+j;
if(back.find(word)!=back.end())
{
completed=true;
range=back.equal_range(word);
for(it2=range.first;it2!=range.second;it2++) //for multiple entries in back
add(it->second,it2->second);
continue;
}
if(temp.find(word)!=temp.end()||dict.find(word)!=dict.end())
{
temp.insert(pair<string,node*>(word,new node(word,it->second)));
dict.erase(word);
}
}
word[i]=letter;
}
}
if(completed)
return result;
temp.swap(front);
}
return result;
}
};