I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Given two words (
beginandend), and a dictionary's word list, find all shortest transformation sequence(s) frombegintoend, such that:Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that
beginis not a transformed word. Note:
- Return an empty list if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume
beginandendare non-empty and are not the same.
Inputs
"hit"
"cog"
["hot","dot","dog","lot","log","cog"]
"hit"
"cog"
["hot","dot","dog","lot","log"]
Outputs
[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
[]
Code
#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
struct Solution {
const inline std::vector<std::vector<std::string>> findLadders(
const std::string begin,
const std::string end,
const std::vector<std::string> &words
) {
std::unordered_set<std::string> dict_words(words.begin(), words.end());
if (dict_words.find(end) == dict_words.end()) {
return {};
}
graph graph;
std::vector<std::vector<std::string>> paths;
std::vector<std::string> path = {begin};
if (make_graph(graph, begin, end, dict_words)) {
find_paths(graph, begin, end, path, paths);
}
return paths;
}
private:
typedef unordered_map<std::string, std::vector<std::string>> graph;
const inline bool make_graph(
graph &graph,
const std::string begin,
const std::string end,
std::unordered_set<std::string> &dict_words
) {
std::unordered_set<std::string> candidate_words;
candidate_words.insert(begin);
while (!candidate_words.empty()) {
if (candidate_words.find(end) != candidate_words.end()) {
return true;
}
for (std::string word : candidate_words) {
dict_words.erase(word);
}
std::unordered_set<std::string> curr_word;
for (std::string word : candidate_words) {
std::string parent = word;
for (int chari = 0; chari < word.size(); chari++) {
char character = word[chari];
for (int letter = 0; letter < 26; letter++) {
word[chari] = 'a' + letter;
if (dict_words.find(word) != dict_words.end()) {
curr_word.insert(word);
graph[parent].push_back(word);
}
}
word[chari] = character;
}
}
std::swap(candidate_words, curr_word);
}
return false;
}
static const inline void find_paths(
graph &graph,
const std::string begin,
const std::string end,
std::vector<std::string> &path,
std::vector<std::vector<std::string>> &paths
) {
if (begin == end) {
paths.push_back(path);
} else {
for (std::string child : graph[begin]) {
path.push_back(child);
find_paths(graph, child, end, path, paths);
path.pop_back();
}
}
}
};