结果还是这个字符串找路径问题!
记录话,想到了map记录到底哪个指针指到它的,结果发现一个字符串可以从多个路径变过来,然后就悲剧,用multimap也不行,看来还是乖乖记录它从哪里来的。
用map错误代码:
记录我天真的使用map,又要修改好多代码了。。
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<string> toPop,toPush;
toPop.push(start);
int depth=0;
int min_depth=-1;
map<string,string> mapDic;
vector<vector<string>> result;
while(!toPop.empty())
{
if(min_depth!=-1) break;
while(!toPop.empty())
{
string begin=toPop.top();
toPop.pop();
for(int i=0;i<begin.length();i++)
{
string begin2=begin;
char c=begin[i];
for(char j='a';j<='z';j++)
{
if(begin[i]==j) continue;
begin[i]=j;
if(begin==end)
{
if(min_depth==-1) min_depth=depth+2;
string begin3=begin2;
std::map<string,string>::iterator it=mapDic.find(begin3);
vector<string> tmp;
tmp.resize(min_depth);
int idx=min_depth-1;
tmp[idx]=end;
idx--;
if(min_depth>=2) tmp[idx--]=begin3;
while(it!=mapDic.end() && it->second!=start)
{
tmp[idx--]=it->second;
begin3=it->second;
it=mapDic.find(begin3);
}
tmp[0]=start;
result.push_back(tmp);
}
std::unordered_set<std::string>::const_iterator got = dict.find (begin);
if(got!=dict.end())
{
toPush.push(begin);
mapDic[begin]=begin2;
}
begin[i]=c;
}
}
}
while(!toPush.empty())
{
string top=toPush.top();
toPush.pop();
toPop.push(top);
dict.erase(top);
}
// swap(toPush,toPop);
depth++;
}
return result;
}
};
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> toPop,toPush;
toPop.push_back(start);
int depth=0;
vector<vector<string>> result;
vector<vector<string>> prevLayer,toPushLayer;
vector<string> tmp;
tmp.push_back(start);
prevLayer.push_back(tmp);
bool find=false;
while(!toPop.empty() && !find)
{
for(int pi=0;pi<toPop.size();pi++)
{
string begin=toPop[pi];
for(int i=0;i<begin.length();i++)
{
char c=begin[i];
for(char j='a';j<='z';j++)
{
if(begin[i]==j) continue;
begin[i]=j;
if(begin==end)
{
if(find==false) toPushLayer.clear();
find=true;
vector<string> tmpVec(prevLayer[pi]);
tmpVec.push_back(begin);
toPushLayer.push_back(tmpVec);
}
else if(find==false)
{
std::unordered_set<std::string>::const_iterator got = dict.find (begin);
if(got!=dict.end())
{
toPush.push_back(begin);
vector<string> tmpVec(prevLayer[pi]);
tmpVec.push_back(begin);
toPushLayer.push_back(tmpVec);
}
}
begin[i]=c;
}
}
}
swap(toPush,toPop);
for(int pi=0;pi<toPop.size();pi++)
{
dict.erase(toPop[pi]);
}
swap(prevLayer,toPushLayer);
depth++;
}
return prevLayer;
}
};
后来想想我每个记录都一团塞进去了真是挺复杂的。。
mark之,有心情再重复解决这个问题。