LeetCode - Word Ladder II

来源:互联网 发布:林弯弯淘宝店铺 编辑:程序博客网 时间:2024/05/01 03:17

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

Return

  [    ["hit","hot","dot","dog","cog"],    ["hit","hot","lot","log","cog"]  ]

class Solution {public:    unordered_map<string,int> wordMap;    vector<string> wordVec;    void constructAdj(vector<vector<int> > &adj){        unordered_map<string,int>::iterator iter=wordMap.begin(),tmp;    while(iter!=wordMap.end()){string s=iter->first;for(int i=0;i<s.size();i++){char t=s[i];for(char c='a';c<='z';c++){if(c!=t){s[i]=c;tmp=wordMap.find(s);if(tmp!=wordMap.end()){adj[iter->second].push_back(tmp->second);}}}s[i]=t;}iter++;}    }void getPath(vector<vector<string> > &result, vector<set<int> > &prev,vector<int> &path,const int &s,int curr){if(curr==s){vector<string> vec;for(int i=path.size()-1;i>=0;i--){vec.push_back(wordVec[path[i]]);}result.push_back(vec);return;}set<int>::iterator iter=prev[curr].begin();while(iter!=prev[curr].end()){path.push_back(*iter);getPath(result,prev,path,s,*iter);path.pop_back();iter++;}}    vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {vector<vector<string> > result;dict.insert(start);dict.insert(end);wordMap.clear();wordVec.clear(); unordered_map<string,int>::iterator ii;unordered_set<string>::iterator iter=dict.begin();int index=0,s=0,e=0,t=0,tmp=0;while(iter!=dict.end()){wordMap.insert(make_pair(*iter,index));wordVec.push_back(*iter);index++;iter++;}ii=wordMap.find(start);s=ii->second;ii=wordMap.find(end);e=ii->second;vector<vector<int> > adj(index,vector<int>());vector<set<int> > prev(index,set<int>());constructAdj(adj);       vector<int> level(index,0);queue<int> wordQueue;wordQueue.push(s);level[s]=1;while(!wordQueue.empty()){tmp=wordQueue.front();if(tmp==e){break;}wordQueue.pop();for(int i=0;i<adj[tmp].size();i++){t=adj[tmp][i];if(level[t]==0){level[t]=level[tmp]+1;wordQueue.push(t);prev[t].insert(tmp);}else if(level[t]==level[tmp]+1){prev[t].insert(tmp);}}}vector<int> path;path.push_back(e);getPath(result,prev,path,s,e);return result;    }};