题解:
1.建设图
2.bfs遍历
class Solution {
public:
int numSimilarGroups(vector<string>& strs) {
std::unordered_map<int, std::vector<int>> graph;
for (int i = 0; i < strs.size(); ++i) {
for (int j = 0; j < strs.size(); ++j) {
if (is_similar(strs[i], strs[j])) {
graph[i].push_back(j);
}
}
}
std::vector<bool> visited(strs.size(), false);
int result = 0;
for (int i = 0; i < strs.size(); ++i) {
if (visited[i]) {
continue;
}
bfs(graph, i, visited);
++result;
}
return result;
}
private:
bool is_similar(const std::string& str1, const std::string& str2) {
int cnt = 0;
for (int i = 0; i < str1.size(); ++i) {
if (str1[i] != str2[i]) {
++cnt;
}
}
return cnt <= 2;
}
void bfs(std::unordered_map<int, std::vector<int>>& graph, int begin, std::vector<bool>& visited) {
std::queue<int> que;
que.push(begin);
visited[begin] = true;
while (!que.empty()) {
auto& f = que.front();
que.pop();
for (auto neighboard : graph[f]) {
if (visited[neighboard]) {
continue;
}
visited[neighboard] = true;
que.push(neighboard);
}
}
}
};