LeetCode 126 Word Ladder II (C++)
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start =
end =
dict =
start =
"hit"
end =
"cog"
dict =
["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | class Solution { void generatePaths(vector<string>& path, vector<vector<string>>& ret, const string& start, const unordered_map<string, vector<string>>& parentmap) { if (path.back() == start) { vector<string> row = path; reverse(row.begin(), row.end()); ret.push_back(row); return; } for (string s: parentmap.at(path.back())) { path.push_back(s); generatePaths(path, ret, start, parentmap); path.pop_back(); } } public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string>> ret; if (start == end) { vector<string> path = {start, end}; ret.push_back(path); return ret; } unordered_map<string, vector<string>> parentmap = {{start, vector<string>()}}; unordered_set<string> current = {start}; unordered_set<string> parent; dict.insert(end); bool matched = false; char letters[] = "abcdefghijklmnopqrstuvwxyz"; while (!matched && !current.empty()) { parent = move(current); current.clear(); for (string s: parent) { dict.erase(s); } while (!parent.empty()) { string parentstr = *(parent.begin()); string curstr = parentstr; parent.erase(curstr); for (int i = 0; i < curstr.length(); ++i) { char save = curstr[i]; for (char c: letters) { if (save == c) continue; curstr[i] = c; if (dict.find(curstr) == dict.end()) continue; current.insert(curstr); parentmap[curstr].push_back(parentstr); if (curstr == end) matched = true; } curstr[i] = save; } } } if (!matched) return ret; vector<string> path = {end}; generatePaths(path, ret, start, parentmap); return ret; } }; |