/*Time Limit Exceeded*/
/*
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
queue<string> tovisit;
tovisit.push(beginWord);
int dist = 1;
int minDist = INT_MAX;
while (!tovisit.empty())
{
int num = tovisit.size();
for (int i = 0; i<num;i++)
{
string curWord = tovisit.front();
if (curWord == endWord) {
return dist;
}
tovisit.pop();
addNextWord(curWord, wordList, tovisit);
}
dist++;
}
return 0;
}
private:
void addNextWord(string curWord, vector<string>& wordList, queue<string>& tovisit)
{
vector<string>::iterator it = std::find(wordList.begin(), wordList.end(), curWord);
if (it != wordList.end())
wordList.erase(it);
char letter;
for (int i = 0; i< curWord.size();i++)
{
letter = curWord[i];
for (int j = 0;j<26;j++)
{
curWord[i] = 'a' + j;
vector<string>::iterator it = std::find(wordList.begin(), wordList.end(), curWord);
if (it != wordList.end())
{
tovisit.push(curWord);
wordList.erase(it);
}
}
curWord[i] = letter;
}
}
};
*/
/*Acception two end BFS*/
/*
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet(wordList.begin(), wordList.end());
if(wordSet.find(endWord) == wordSet.end()) return 0;
unordered_set<string> s1, s2;
s1.insert(beginWord);
s2.insert(endWord);
int ans = 1;
while(!s1.empty() && !s2.empty())
{
ans++;
if(s1.size() > s2.size()) swap(s1, s2);
unordered_set<string> temp;
for(auto it = s1.begin(); it != s1.end(); it++)
{
string w = *it;
for(int i = 0; i < w.size(); i++)
{
char c = w[i];
for(int j = 0; j < 26; j++)
{
w[i] = 'a' + j;
if(s2.find(w) != s2.end()) return ans;
if(wordSet.find(w) != wordSet.end())
{
temp.insert(w);
wordSet.erase(w);
}
}
w[i] = c;
}
}
swap(s1, temp);
}
return 0;
}
};
*/
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
queue<string> tovisit;
tovisit.push(beginWord);
int dist = 1;
map<string,string> mpdic;
for(string m:wordList)
{
mpdic[m]=m;
}
while (!tovisit.empty())
{
int num = tovisit.size();
for (int i = 0; i<num;i++)
{
string curWord = tovisit.front();
if (curWord == endWord) {
return dist;
}
tovisit.pop();
addNextWord(curWord, mpdic, tovisit);
}
dist++;
}
return 0;
}
private:
void addNextWord(string curWord, map<string,string>& wordList, queue<string>& tovisit)
{
wordList.erase(curWord);
char letter;
for (int i = 0; i< curWord.size();i++)
{
letter = curWord[i];
for (int j = 0;j<26;j++)
{
curWord[i] = 'a' + j;
if (wordList.count(curWord))
{
tovisit.push(curWord);
wordList.erase(curWord);
}
}
curWord[i] = letter;
}
}
};