737. Sentence Similarity II
// DFS
bool dfs(unordered_map<string, unordered_set<string> >& graph, const string& source, const string& target, unordered_set<string>& visited) {
if (graph[source].count(target)) return true;
if (!visited.count(source)) {
visited.insert(source);
for (const string& next : graph[source]) {
if (!visited.count(next) && dfs(graph, next, target, visited)) return true;
}
}
return false;
}
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<vector<string>>& pairs) {
if (words1.size() != words2.size()) return false;
unordered_map<string, unordered_set<string> > pair_mp;
for (const vector<string>& pair : pairs) {
pair_mp[pair[0]].insert(pair[1]);
pair_mp[pair[1]].insert(pair[0]);
}
unordered_set<string> visited;
for (size_t i = 0; i < words1.size(); ++i) {
if (words1[i] == words2[i]) continue;
visited.clear();
if (!pair_mp.count(words1[i]) || !dfs(pair_mp, words1[i], words2[i], visited)) return false;
}
return true;
}Last updated