Copy void getDiff1s(string s, unordered_set< string> &adjlist , const unordered_set< string> &dict )
{
for(int i = 0; i < s.length(); i++)
{
string strback(s );
for(char c = 'a'; c <= 'z'; c++)
{
strback[i] = c;
auto it = dict .find(strback);
if(it != dict .end() && *it != s && adjlist.find(*it) == adjlist .end())
adjlist.insert(strback);
}
}
}
void genResult(int level, int targetLen , string end, vector <string> & path, std::unordered_map <string, unordered_set<std::string >> &adjList, vector<vector <string> > & result)
{
string curStr = path[path .size() - 1];
if(level == targetLen)
{
if(curStr == end )//!!IMPORTANT
result.push_back(path );
return;
}
for(auto it = adjList[curStr].begin(); it != adjList [curStr].end(); ++it)
{
path.push_back(*it);
genResult( level+1, targetLen , end, path, adjList, result);
path.pop_back();
}
}
vector<vector <string>> findLadders( string start , string end, unordered_set <string> & dict)
{
std::unordered_map< string, unordered_set <std::string>> adjList;
if(dict.find( end) != dict .end()) dict.insert( end);
if(dict.find( start) != dict .end()) dict.erase( start);
//build adjList
unordered_set< string> twoLevels[2];
twoLevels[0].insert( start);
int level = 0;
while ( true)
{
unordered_set<string > &lastLevel = twoLevels[level % 2];
unordered_set<string > &nextLevel = twoLevels[(level+1) % 2];
nextLevel.clear();
for(auto it = lastLevel.begin(); it != lastLevel.end(); ++it)
{
unordered_set<string > adj;
getDiff1s(*it, adj, dict);
adjList[*it] = adj;
nextLevel.insert(adj.begin(), adj.end()); //if the same, will not insert
}
if(nextLevel.size() == 0)
return vector <vector< string>>();// no result
//can remove the ones in dict of the current level,
for(auto it = nextLevel.begin(); it != nextLevel.end(); ++it)
dict.erase(*it);//erase by key
++level;
if(nextLevel.find(end ) != nextLevel.end())//find the smallest path
break;
}
vector< vector<string > > result;
vector< string> path(1, start );
//adjList contains the smallest path, but not all the path is valid,
//valid: path's length is level AND the last one is end
genResult(0, level, end, path, adjList, result);
return move(result);
}