Note:
1. When tracing the path, the tracing depth is controlled based on the maximum length of the path.
2. In BFs, after finding the End Word, mark the current layer with "find = true" and end after traversing the current layer. You do not need to repeat the next layer.
3. words in the dictionary can be deleted to replace the set of visited. In this way, the optimization time will be reduced from 1700 MS + to 800 ms +.
The Code is as follows:
class Solution {public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { set<string> queue[2]; queue[0].insert(start); vector<vector<string>> res; bool find = false; int length = 1; bool cur = false; map<string, set<string>> mapping; //bfs while (queue[cur].size() && !find) { length++; for (set<string>::iterator i = queue[cur].begin(); i != queue[cur].end(); i++)//delete from dictionary dict.erase(*i); for (set<string>::iterator i = queue[cur].begin(); i != queue[cur].end(); i++) { for (int l = 0; l < (*i).size(); l++) { string word = *i; for (char c = 'a'; c <= 'z'; c++) { word[l] = c; if (dict.find(word) != dict.end()) { if (mapping.find(word) == mapping.end()) mapping[word] = set<string>(); mapping[word].insert(*i); if (word == end) find = true; else queue[!cur].insert(word); } } } } queue[cur].clear(); cur = !cur; } if (find) { vector<string> temp; temp.push_back(end); getRes(mapping, res, temp, start, length); } return res; } void getRes(map<string, set<string>> & mapping, vector<vector<string>> & res, vector<string> temp, string start, int length) { if (temp[0] == start) { res.push_back(temp); return; } if (length == 1) return;//recursion depth string word = temp[0]; temp.insert(temp.begin(), ""); for (set<string>::iterator j = mapping[word].begin(); j != mapping[word].end(); j++) { temp[0] = *j; getRes(mapping, res, temp, start, length - 1); } }};
Word ladder II [leetcode]