http://oj.leetcode.com/problems/word-ladder-ii/
class Solution { public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { //map <string,string> parentRecord; multimap<string ,string> parentRecord; queue<pair<string ,int > > wordQueue; unordered_set<string> visited; wordQueue.push(make_pair(start,1)); visited.insert(start); parentRecord.insert(make_pair(start,"0")); int flag = 0; int length = 0; int flag2 = 0; while(!wordQueue.empty()) { string curStr = wordQueue.front().first; int curStep = wordQueue.front().second; if(flag ==1 ) { if(curStep != length) break; } wordQueue.pop(); for(int i = 0;i<curStr.size();i++) { if(flag2 == 1) { flag2 = 0; break; } string tmp = curStr; for(int j = 0;j<26;++j) { flag2 = 0; tmp[i] = j+'a'; if(tmp == end) { // return curStep+1; parentRecord.insert(make_pair(tmp,curStr)); flag = 1; length = curStep; flag2 = 1; wordQueue.push(make_pair(tmp,curStep+1)); visited.insert(tmp); break; } if(visited.find(tmp) == visited.end() && dict.find(tmp)!=dict.end()) { wordQueue.push(make_pair(tmp,curStep+1)); visited.insert(tmp); parentRecord.insert(make_pair(tmp,curStr)); } } } } vector<vector<string> > ansVector; ansVector.clear(); vector<string> onePiece; string str1 = end,str2; multimap<string,string>::iterator iter; int ii = parentRecord.count(end); vector<string> another; another.clear(); for(int i = 0;i<ii;i++) { str1 = end; onePiece.clear(); another.clear(); while(1) { onePiece.push_back(str1); iter = parentRecord.find(str1); if( str1 == start) { for(int it = onePiece.size()-1;it>=0;it--) another.push_back(onePiece[it]); ansVector.push_back(another); break; } str2 = (*iter).second; if(parentRecord.count(str1)>1) parentRecord.erase(iter); str1 = str2; } } return ansVector; } };
在visited那的处理那里弄错了,应该是更广一些。暂时不想改,先这样。
用到了multimap.因为map的话,key是唯一的,只能存储(cog,dog)不能一起存储(cog,dog),(cog,log).