Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
简单bfs
直接从beginWord开始宽搜
要加一个优化才能保证不TLE:当整体都向外走了一步时,把上一步走过的单词都从List里面删掉,能大量减少状态数
class Solution {
public:
int ans;
vector<int> pre;
vector<string> del;
vector<vector<string> > Ans;
map<string,int> strtonum;
map<int,string> numtostr;
vector<vector<string> > findLadders(string beginWord, string endWord, unordered_set<string> &wordList)
{
if(wordList.count(endWord)==0)wordList.insert(endWord);
int len = 0 ;
for(unordered_set<string>::iterator iter=wordList.begin();iter!=wordList.end();iter++)
{
strtonum[*iter] = ++len;
numtostr[len] = *iter;
}
pre.push_back(-1);
ans = len;
int st = 0 , ed = 0 , last = 0;
vector<pair<string,int>> q;
q.push_back(make_pair(beginWord,0));
while(st<=ed)
{
int step = q[st].second;
string str = q[st].first;
if(last != step)
{
last = step;
for(int i=0;i<del.size();i++)
wordList.erase(del[i]);
del.clear();
}
if(step < ans)
{
for(int i=0;i<str.size();i++)
{
string cnt = str;
for(char j='a';j<='z';j++)if(str[i]!=j)
{
cnt[i] = j;
auto iter = wordList.find(cnt);
if( iter != wordList.end() && cnt != beginWord)
{
del.push_back(cnt);
ed++;
q.push_back(make_pair(cnt,step+1));
pre.push_back(st);
if(cnt == endWord)
{
ans = step+1;
vector<string> vec;
vec.push_back(endWord);
int x = st;
while(x!=-1)
{
vec.push_back(q[x].first);
x = pre[x];
}
reverse(vec.begin(),vec.end());
Ans.push_back(vec);
}
}
}
}
}
st++;
}
return Ans;
}
};