搜索的时候,需要用dfs搜素,找到是否真的存在
class Solution {
public:
// using a to find b
bool judge(string a, string b, map<string, set<string>>& maps, set<string>& visit)
{
if(a==b)
return true;
visit.insert(a); // a is searched
set<string> temp = maps[a];
for( set<string>::iterator it = temp.begin();it!=temp.end();++it)
{
if(visit.find(*it)==visit.end())
{
visit.insert(*it);
if(judge(*it, b, maps, visit))
return true;
}
}
return false;
}
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
if(words1.size()!=words2.size())
return false;
map<string, set<string>> maps;
for(int i=0;i<pairs.size();i++)
{
string a = pairs[i].first;
string b = pairs[i].second;
if(maps.find(a)==maps.end())
{
set<string> temp;
temp.insert(b);
maps[a] = temp;
}
else
maps[a].insert(b);
if(maps.find(b)==maps.end())
{
set<string> temp;
temp.insert(a);
maps[b] = temp;
}
else
maps[b].insert(a);
}
/*
for(map<string, set<string>>::iterator it = maps.begin();it!=maps.end();++it)
{
cout<<it->first;
set<string> temp = it->second;
for (std::set<string>::iterator its=temp.begin(); its!=temp.end(); ++its)
cout << " "<< *its;
cout<<endl;
}*/
set<string> visit;
for(int i=0;i<words1.size();i++)
{
if(judge(words1[i], words2[i], maps, visit)==false)
return false;
visit.clear();
}
return true;
}
};