Connected Component in Undirected Graph
Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.)
S: DFS
dfs找到所有关联节点
/**
* Definition for Undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
vector<vector<int>> connectedSet(vector<UndirectedGraphNode*>& nodes) {
vector<vector<int>> result;
for(const auto& node : nodes) {
if (!visited[node->label]) {
visited[node->label] = true;
vector<int> curSet{node->label};
dfs(node, curSet);
sort(curSet.begin(), curSet.end());
result.push_back(curSet);
}
}
return result;
}
void dfs(UndirectedGraphNode* node, vector<int>& set) {
for (const auto& i : node->neighbors) {
if (!visited[i->label]) {
visited[i->label] = true;
set.push_back(i->label);
dfs(i, set);
}
}
}
private:
unordered_map<int, bool> visited;
};