1. 程式人生 > >Leetcode 126. 單詞接龍 II

Leetcode 126. 單詞接龍 II

cto color rds lse leetcode tmp stp pre !=

class Solution {
public:    
    void getShortestPaths(string cur,
                      string ed,
                      map<string, vector<string>> &nexts,
                      map<string, int> &distances,
                      vector<string> &solution,
                      vector
<vector<string>> &res) { solution.push_back(cur); if (cur == ed) { res.push_back(solution); } else { auto vec_it = nexts.find(cur)->second; for(auto it=vec_it.begin(); it!= vec_it.end(); ++it) {
if(distances.find(*it)->second == distances.find(cur)->second + 1) getShortestPaths(*it, ed, nexts, distances, solution, res); } } solution.pop_back(); } map<string, int> getDistances(string beg, map<string, vector<string
>> &nexts) { map<string, int> distance; set<string> aux; queue<string> que; que.push(beg); distance.insert(make_pair(beg, 0)); aux.insert(beg); while(!que.empty()) { string tmp = que.front(); que.pop(); auto vec_it = nexts.find(tmp)->second; for(auto it = vec_it.begin(); it!= vec_it.end(); ++it ) { if(aux.find(*it) == aux.end()) { distance.insert(make_pair(*it, distance.find(tmp)->second+1 )); que.push(*it); aux.insert(*it); } } } return distance; } vector<string> getNext(string word, const set<string> &dict) { vector<string> res; for(int i=0; i<word.size(); ++i) { for(char cur = a; cur <= z; ++cur) { if(word[i] != cur) { string tmp = word; tmp[i] = cur; if(dict.find(tmp) != dict.end()) { res.push_back(tmp); } } } } return res; } map<string, vector<string>> getNexts(const vector<string> &words) { set<string> dict(words.begin(), words.end()); map<string, vector<string>> nexts; for(int i=0; i<words.size(); ++i) { nexts.insert(make_pair(words[i], getNext(words[i], dict))); } return nexts; } vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) { wordList.push_back(beginWord); auto nexts = getNexts(wordList); auto distances = getDistances(beginWord, nexts); vector<string> path; vector<vector<string>> res; getShortestPaths(beginWord, endWord, nexts, distances, path, res); return res; } };

Leetcode 126. 單詞接龍 II