Find the Weak Connected Component in the Directed Graph
2015-09-11 01:50
477 查看
Description:
Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.)
Example
Given graph:
A----->B C \ | | \ | | \ | | \ v v ->D E <- F
Return {A,B,D}, {C,E,F}. Since there are two connected component which are {A,B,D} and {C,E,F}
Solution:
( Union-Find Sets )/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { private: unordered_map<DirectedGraphNode*, DirectedGraphNode*> cache; DirectedGraphNode* find(DirectedGraphNode* node) { if (cache[node] != node) cache[node] = find(cache[node]); return cache[node]; } void merge(DirectedGraphNode* n1, DirectedGraphNode* n2) { auto f1 = find(n1); auto f2 = find(n2); if (f1 != f2) cache[f2] = f1; } public: /** * @param nodes a array of directed graph node * @return a connected set of a directed graph */ vector<vector<int>> connectedSet2(vector<DirectedGraphNode*>& nodes) { vector<vector<int>> rc; for (auto& node : nodes) cache[node] = node; for (auto& node : nodes) for (auto& ngb : node->neighbors) merge(node, ngb); unordered_map<DirectedGraphNode*, int> index; for (auto& node : nodes) { auto father = find(node); if (index.find(father) == index.end()) { rc.push_back(vector<int>({node->label})); index[father] = rc.size()-1; } else rc[index[father]].push_back(node->label); } return rc; } };
相关文章推荐
- Http访问 两种请求(POST与GET)以及错误解决
- ubuntu设置系统时间与网络时间同步
- Leetcode Merge Two Sorted Lists
- 【Python基础】Python面向对象 - 4 - 定制类的特殊方法
- [20150911]el表达式跟ognl表达式的区别
- Leetcode Maximum Subarray
- tcp/ip协议入门
- ECMAScript 6 Features 中文版
- 给定一个数组input[] ,如果数组长度n为奇数,则将数组中最大的元素放到 output[] 数组 最中间的位置,如果数组长度n为偶数,则将数组中最大的元素放到 output[] 数组中间两个位置偏右的那个位置上
- UITableView的使用
- 测试
- 使用YUM安装MySQL 5.5(适用于CentOS6.2/5.8及Fedora 17/16平台)
- Flume学习1_Flume NG架构设计要点及配置实践
- 2015-09-09 [一点资讯]--数据抓取和处理工程师--2面
- Sliding Window Maximum
- 创建DOM节点prepend()、prependTo()
- BZOJ 1607([Usaco2008 Dec]Patting Heads 轻拍牛头-线性筛)
- 中断 定时器 实现 sleep
- iOS UIButton 设置图片文字垂直排列
- java中mongodb的查询及排序