431. Connected Component in Undirected Graph
中文English
Find connected component in undirected graph.
Each node in the graph contains a label and a list of its neighbors.
(A connected 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.)
You need return a list of label set.
Example
Example 1:
Input: {1,2,4#2,1,4#3,5#4,1,2#5,3}
Output: [[1,2,4],[3,5]]
Explanation:
1------2 3
\ | |
\ | |
\ | |
\ | |
4 5
Example 2:
Input: {1,2#2,1}
Output: [[1,2]]
Explanation:
1--2
Clarification
Learn more about representation of graphs
Notice
Nodes in a connected component should sort by label in ascending order. Different connected components can be in any order.
Input test data (one parameter per line)How to understand a testcase?
解法1:BFS
代码如下:
/**
* Definition for Undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/*
* @param nodes: a array of Undirected graph node
* @return: a connected set of a Undirected graph
*/
vector<vector<int>> connectedSet(vector<UndirectedGraphNode*> nodes) {
if (nodes.size() == 0) return result;
for (auto node : nodes) visited[node] = 0;
for (auto node : nodes) {
if (!visited[node]) {
visited[node] = 1;
bfs(node, nodes);
}
}
return result;
}
private:
void bfs(UndirectedGraphNode * node, vector<UndirectedGraphNode *> nodes)
{
queue<UndirectedGraphNode *> q;
q.push(node);
vector<int> component;
component.push_back(node->label);
while(!q.empty()) {
UndirectedGraphNode * topNode = q.front();
q.pop();
for (int i = 0; i < topNode->neighbors.size(); ++i) {
if (visited[topNode->neighbors[i]]) continue;
visited[topNode->neighbors[i]] = 1;
q.push(topNode->neighbors[i]);
component.push_back(topNode->neighbors[i]->label);
}
}
sort(component.begin(), component.end());
result.push_back(component);
}
vector<vector<int>> result;
map<UndirectedGraphNode *, int> visited;
};
解法2:DFS
TBD
解法3:Union Find
TBD