Problem
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.)
Clarification
Learn more about representation of graphsExample
Given graph:A------B C \ | | \ | | \ | | \ | | D E
Return
{A,B,D}
,{C,E}
. Since there are two connected component which is{A,B,D}, {C,E}
Solution
DFS找出联通块
/**
* Definition for Undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
private:
set<int> visited;
public:
/**
* @param nodes a array of Undirected graph node
* @return a connected set of a Undirected graph
*/
vector<vector<int>> connectedSet(vector<UndirectedGraphNode*>& nodes) {
vector<vector<int>> ret;
for(int i = 0; i < nodes.size(); i++) {
if (visited.count(nodes[i]->label) == 0) {
vector<int> res;
visited.insert(nodes[i]->label);
dfs(nodes[i], res);
sort(res.begin(), res.end());
ret.push_back(res);
}
}
return ret;
}
void dfs(UndirectedGraphNode *node, vector<int> &res) {
res.push_back(node->label);
for(int i = 0; i < node->neighbors.size(); i++) {
int label = node->neighbors[i]->label;
if (visited.count(label) == 0) {
visited.insert(label);
dfs(node->neighbors[i], res);
}
}
}
};
网友评论