LeetCode Word Ladder II
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 = "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.
class Solution { private: vector<vector<string>> res; public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { res.clear(); unordered_map<string, vector<string> > paths; queue<string> que; que.push(start); dict.insert(end); vector<string> del; del.push_back(start); while (!que.empty()) { int size = que.size(); for (string& s : del) { dict.erase(s); } del.clear(); for (int i=0; i<size; i++) { string str = que.front(); string orig = str; que.pop(); if (str == end) { continue; } for (char& ch : str) { for (char c = 'a'; c <= 'z'; c++) { if (ch == c) { continue; } char t = ch; ch = c; if (dict.count(str) > 0) { del.push_back(str); que.push(str); if (paths.count(str) == 0) { paths.insert(make_pair(str, vector<string>())); } paths[str].push_back(orig); } ch = t; } } } } vector<string> path; path.push_back(end); build_path(paths, path, end); return res; } void build_path(unordered_map<string, vector<string> > paths, vector<string>& path, string prev) { if (paths.count(prev) == 0) { if (path.size() < 2) return; reverse(path.begin(), path.end()); res.push_back(path); return; } vector<string>& strs = paths[prev]; for (string& s : strs) { path.push_back(s); build_path(paths, path, s); path.pop_back(); } } };
TLE