//very interesting problem
//It can be solved with standard BFS. The tricky idea is doing BFS of paths instead of words!
//Then the queue becomes a queue of paths.
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList)
{
vector<vector<string>> ans;
if (wordList.size() == 0) return ans;
unordered_set<string> setWordList;
for (auto str : wordList) setWordList.insert(str);
if (!setWordList.count(endWord)) return ans;
return findLadders(beginWord, endWord, setWordList);
};
private:
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList)
{
vector<vector<string>> ans;
queue<vector<string>> paths;
vector<string> path;
paths.push({ beginWord });
int minStep = INT_MAX;
int level = 1;
unordered_set<string> visited;
//"visited" records all the visited nodes on this level
//these words will never be visited again after this level
//and should be removed from wordList. This is guaranteed
// by the shortest path.
while (!paths.empty())
{
path = paths.front();
paths.pop();
if(path.size()>level)
{
level = path.size();
if(level >minStep) break;
else
{
//"visited" records all the visited nodes on this level
//these words will never be visited again after this level
//and should be removed from wordList. This is guaranteed
//by the shortest path.
for(auto str : visited) wordList.erase(str);
visited.clear();
}
}
string lastWord = path.back();
for (int i = 0; i<lastWord.size();i++)
{
string newWord = lastWord;
for (int j = 0; j<26;j++)
{
char c = newWord[i];
c = 'a' + j;
newWord[i] = c;
//if(newWord == lastWord) continue; no need.
if (wordList.count(newWord))
{
vector<string> newPath = path;
newPath.push_back(newWord);
visited.insert(newWord);
if (newWord == endWord)
{
int step = newPath.size();
ans.push_back(newPath);
minStep = min(minStep, step);
}
else
{
paths.push(newPath);
}
}
}
}
}
return ans;
}
};
void main()
{
cout << sizeof(string) << endl;
cout << sizeof(int) << endl;
/*
string strBegin = "hit";
string strEnd = "cog";
vector<string> strDic{ "hot","dot","dog","lot","log","cog" };
*/
//["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"]
string strBegin = "red";
string strEnd = "tax";
vector<string> strDic{ "ted", "tex", "red", "tax", "tad", "den", "rex", "pee" };
Solution().findLadders(strBegin,strEnd,strDic);
}