以为是广度优先,结果有环的图的递归果然还是包括深度优先了!所以以下代码悲剧错了!!!
class Solution {
public:
int min_depth;
void dfs(string &start,string &end, unordered_set<string> &dict,int depth)
{
if(min_depth!=INT_MAX) return;
if(start==end) min_depth=depth;
vector<string> toDetect;
for(int i=0;i<start.length();i++)
{
char c=start[i];
for(char j='a';j<='z';j++)
{
if(start[i]==j) continue;
start[i]=j;
std::unordered_set<std::string>::const_iterator got = dict.find (start);
if(got!=dict.end())
{
toDetect.push_back(start);
dict.erase(got);
}
start[i]=c;
}
}
for(int i=0;i<toDetect.size();i++)
{
dfs(toDetect[i],end,dict,depth+1);
}
}
int ladderLength(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
min_depth=INT_MAX;
dfs(start,end,dict,1);
if(min_depth==INT_MAX) return 0;
return min_depth;
}
};
哎,还是完全模仿网上代码!没有原创性。
学习了swap函数的使用。
更加熟悉了dfs,bfs区别。
class Solution {
public:
int ladderLength(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;
while(!toPop.empty())
{
while(!toPop.empty())
{
string begin=toPop.top();
toPop.pop();
if(begin==end) return depth+1;
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;
std::unordered_set<std::string>::const_iterator got = dict.find (begin);
if(got!=dict.end())
{
toPush.push(begin);
dict.erase(got);
}
begin[i]=c;
}
}
}
swap(toPush,toPop);
depth++;
}
return 0;
}
};