Approach
Breadth-first search
For Synonymous Sentences, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 57 lines of C++ from the credited upstream file 1258.cpp.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<string> generateSentences(vector<vector<string>>& synonyms,4 string text) {5 set<string> ans;6 unordered_map<string, vector<string>> graph;7 queue<string> q{{text}};8 9 for (const vector<string>& synonym : synonyms) {10 const string& s = synonym[0];11 const string& t = synonym[1];12 graph[s].push_back(t);13 graph[t].push_back(s);14 }15 16 while (!q.empty()) {17 const string u = q.front();18 q.pop();19 ans.insert(u);20 vector<string> words = split(u);21 for (string& word : words) {22 const auto it = graph.find(word);23 if (it == graph.cend())24 continue;25 for (const string& synonym : it->second) {26 27 word = synonym;28 const string newText = join(words, ' ');29 if (!ans.contains(newText))30 q.push(newText);31 }32 }33 }34 35 return {ans.begin(), ans.end()};36 }37 38 private:39 vector<string> split(const string& s) {40 vector<string> words;41 istringstream iss(s);42 for (string token; iss >> token;)43 words.push_back(token);44 return words;45 }46 47 string join(const vector<string>& words, char c) {48 string joined;49 for (int i = 0; i < words.size(); ++i) {50 joined += words[i];51 if (i != words.size() - 1)52 joined += c;53 }54 return joined;55 }56};57