/*************************************************************************
* File Name: Solution.cpp
* Description:
* Author: Yuji CAO
* Mail: caoyuji@sogou-inc.com
* Created_Time: 2015-07-31 10时13分23秒
* Last modified: 2015-07-31 10时13分23秒
************************************************************************/
#include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<unordered_map>
#include<unordered_set>
using namespace std;
class Solution{
public:
int ladderPath(unordered_set<string>& dic,string &src,string &dst){
dic.insert(dst);
dic.insert(src);
queue<string> q;
q.push(src);
_color.insert(src);
while(!q.empty()){
string tmp=q.front();
q.pop();
for(int i=0;i<(int)tmp.length();++i){
for(char ele='a';ele<='z';++ele){
if(ele!=tmp[i]){
string adjTmp(tmp);
adjTmp[i]=ele;
if(dic.find(adjTmp)!=dic.end()){
if(_color.find(adjTmp)==_color.end()){//没有访问过的临节点
_parent[adjTmp]=tmp;
_color.insert(adjTmp);
q.push(adjTmp);
}
}
}
}
}
}
int pathLen=0;
printPath(src,dst,pathLen);
return pathLen;
}
void printPath(string& src,string& dst,int &pathLen){
cout<<src.c_str();
printPath(dst,pathLen);
}
void printPath(string& dst,int &pathLen){
if(_parent.find(dst)==_parent.end()){
//cout<<endl;
return;
}
printPath(_parent[dst],pathLen);
cout<<"->"<<dst.c_str();
pathLen++;
}
private:
unordered_set<string> _color;
unordered_map<string,string> _parent;
};
int main(){
Solution s;
string d[]={"hot","log","dot","dog","lot"};
vector<string> dat(d,d+5);
unordered_set<string> dic(dat.begin(),dat.end());
string start("hit");
string end("cog");
int len=s.ladderPath(dic,start,end);
cout<<"\npath-length:"<<len<<endl;
return 0;
}
分析
在不构造图数据的情况下模拟图的广度优先便历,是本题的难点!