1
// BFS gives TLE if we store path while traversing because whenever we find a2
// better visit time for a word, we have to clear/make a new path vector3
// everytime. The idea is to first use BFS to search from beginWord to endWord4
// and generate the word-to-children mapping at the same time. Then, use DFS5
// (backtracking) to generate the transformation sequences according to the6
// mapping. The reverse DFS allows us to only make the shortest paths, never7
// having to clear a whole sequence when we encounter better result in BFS No8
// string operations are done, by dealing with indices instead.12
bool able(string s, string t) {14
for (int i = 0; i < s.length(); i++) c += (s[i] != t[i]);17
void bfs(vector<vector<int>> &g, vector<int> parent[], int n, int start, int end) {18
vector<int> dist(n, 1005);27
if (dist[u] > dist[x] + 1) {28
dist[u] = dist[x] + 1;31
parent[u].push_back(x);32
} else if (dist[u] == dist[x] + 1)33
parent[u].push_back(x);37
void shortestPaths(vector<vector<int>> &Paths, vector<int> &path, vector<int> parent[],40
// as parent of start was -1, we've completed the backtrack41
Paths.push_back(path);44
for (auto u : parent[node]) {46
shortestPaths(Paths, path, parent, u);50
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList) {51
// start and end are indices of beginWord and endWord52
int n = wordList.size(), start = -1, end = -1;53
vector<vector<string>> ANS;54
for (int i = 0; i < n; i++) {55
if (wordList[i] == beginWord) start = i;56
if (wordList[i] == endWord) end = i;59
// if endWord doesn't exist, return empty list60
if (end == -1) return ANS;62
// if beginWord doesn't exist, add it in start of WordList64
wordList.emplace(wordList.begin(), beginWord);69
// for each word, we're making adjency list of neighbour words (words that70
// can be made with one letter change) Paths will store all the shortest71
// paths (formed later by backtracking)72
vector<vector<int>> g(n, vector<int>()), Paths;74
// storing possible parents for each word (to backtrack later), path is the75
// current sequence (while backtracking)76
vector<int> parent[n], path;78
// creating adjency list for each pair of words in the wordList (including80
for (int i = 0; i < n - 1; i++)81
for (int j = i + 1; j < n; j++)82
if (able(wordList[i], wordList[j])) {87
bfs(g, parent, n, start, end);89
// backtracking to make shortestpaths90
shortestPaths(Paths, path, parent, end);91
for (auto u : Paths) {93
for (int i = 0; i < u.size() - 1; i++) now.push_back(wordList[u[i]]);94
reverse(now.begin(), now.end());95
now.push_back(wordList[end]);