题目描述
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
//dfs做的,调试没问题,超时了-_-
class Solution {
public:
void dfs(string start, string end,unordered_set<string> &dict
,int &step,map<string,int>&mp,bool &flag)
{
if(diff(start,end))
{
++step;
flag=true;
return ;
}
for(auto j:dict)
{
string temp=start;
if(diff(j,start)&&mp[j]==0)
{
mp[j]=1;
++step;
start=j;
dfs(start,end,dict,step,mp,flag);
if(flag) return ;
--step;
start=temp;
mp[j]=0;
}
}
}
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start==end) return 2;
map<string,int>mmp;
for(auto i:dict)
mmp[i]=0;
int step=1;
bool flag=false;
dfs(start,end,dict,step,mmp,flag);
if(flag) return step;
else return 0;
}
private:
bool diff(string x,string y)
{
if(abs(x.size()-y.size())>1) return false;
int cnt=0;
int MinSize=min(x.size(),y.size());
for(int i=0;i<MinSize;++i)
{
if(x[i]!=y[i]) ++cnt;
}
if(cnt==1&&x.size()==y.size())
return true;
if(cnt==0&&x.size()!=y.size())
return true;
return false;
}
};
//利用bfs
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start==end) return 2;
dict.erase(start);
dict.insert(end);
map<string,int>mp;
for(auto i:dict)
mp[i]=0;
int step=0;
queue<string>q;
q.push(start);
while(!q.empty())
{
++step;
int len=q.size();
vector<string>delet;
for(int i=0;i<len;++i)
{
string front=q.front();
q.pop();
if(front==end) return step;
for(auto j:dict)
{
if(diff(front,j)==1&&mp[j]==0)
{
q.push(j);
mp[j]=1;
delet.push_back(j);
}
}
for(int k=0;k<delet.size();++k)
dict.erase(delet[k]);
}
}
return 0;
}
private:
int diff(string s1,string s2)
{
int count=0;
for(int i=0;i<s1.size();i++)
{
if(s1[i]!=s2[i]) count++;
}
return count;
}
};