请找出无向图中相连要素的个数。
图中的每个节点包含其邻居的 1 个标签和 1 个列表。(一个无向图的相连节点(或节点)是一个子图,其中任意两个顶点通过路径相连,且不与超级图中的其它顶点相连。)
样例
给定图:
A------B C
\ | |
\ | |
\ | |
\ | |
D E
返回 {A,B,D}, {C,E}
。其中有 2 个相连的元素,即{A,B,D}, {C,E}
/**
* 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) {
// Write your code here
int n = nodes.size();
map<UndirectedGraphNode*, bool> flags;
for (int i = 0; i < nodes.size(); i++)
{
flags[nodes[i]] = false;
}
vector<vector<int> > result;
vector<UndirectedGraphNode*> buf;
for (int i = 0; i < nodes.size(); i++)
{
if (flags[nodes[i]])
{
continue;
}
buf.clear();
buf.push_back(nodes[i]);
flags[nodes[i]] = true;
visit(nodes[i], 0, flags, buf);
vector<int> temp;
for (int i = 0; i < buf.size(); i++)
{
temp.push_back(buf[i]->label);
}
sort(temp.begin(), temp.end());
result.push_back(temp);
}
return result;
}
private:
void visit(UndirectedGraphNode *p, int pos,
map<UndirectedGraphNode*, bool> &flags, vector<UndirectedGraphNode*> &buf)
{
if (pos >= buf.size())
{
return;
}
int n = p->neighbors.size();
for (int i = 0; i < n; i++)
{
UndirectedGraphNode *q = p->neighbors[i];
if (flags.find(q) != flags.end() && !flags[q])
{
flags[q] = true;
buf.push_back(q);
}
}
int m = buf.size();
visit(buf[pos+1], pos+1, flags, buf);
}
};