[LintCode] Find the Weak Connected Component in the Directed Graph
2015-09-01 19:36
435 查看
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:
Return
Note
Sort the element in the set in increasing order.
Solution:
并查集。遍历每一条变,更新每个节点所在集合。
Inspired by: http://www.cnblogs.com/easonliu/p/4607300.html
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}
Note
Sort the element in the set in increasing order.
Solution:
并查集。遍历每一条变,更新每个节点所在集合。
/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { //use union-set to solve private: int find(unordered_map<int, int> &nodeMap, int label){ if(nodeMap.find(label) == nodeMap.end()){ nodeMap[label] = label; return label; //if this node doesn't belong to any union-set, create a new set }else{ //this node belongs to some set, find the root of the set int res = nodeMap[label]; while(nodeMap[res] != res) res = nodeMap[res]; return res; } } public: /** * @param nodes a array of directed graph node * @return a connected set of a directed graph */ vector<vector<int>> connectedSet2(vector<DirectedGraphNode*>& nodes) { unordered_map<int, int> nodeMap; vector<vector<int> > result; for(int i = 0;i < nodes.size();++i){ for(int j = 0;j < (nodes[i]->neighbors).size();++j){ int s1 = find(nodeMap, nodes[i]->label); int s2 = find(nodeMap, (nodes[i]->neighbors)[j]->label); if(s1 != s2){ //union two sets if(s1 < s2) nodeMap[s2] = s1; else nodeMap[s1] = s2; }else{ //do nothing } } } unordered_map<int, int> setId2VecId; for(int i = 0;i < nodes.size();++i){ int label = nodes[i]->label; int setId = find(nodeMap, label); if(setId2VecId.find(setId) == setId2VecId.end()){ vector<int> vec; setId2VecId[setId] = result.size(); result.push_back(vec); } int idx = setId2VecId[setId]; result[idx].push_back(label); } for(int i = 0;i < result.size();++i) sort(result[i].begin(), result[i].end()); return result; } };
Inspired by: http://www.cnblogs.com/easonliu/p/4607300.html
相关文章推荐
- [Leetcode] Different Ways to Add Parentheses
- VIM配置笔记(cscope+NERDTree)
- Safari的常用快捷键
- 我的程序员未婚夫
- 【UVA796】【无向图割边】
- Windows 端口和任务 查看 相关命令
- CRgn::CreateEllipticRgnIn
- 第三方加载图片
- 获取本机外网ip获取位置
- 散列操作的基本例程(1)
- react-native试玩(6)-日期选择控件
- hdu 2002 计算球体积
- oracle 学习sql
- OC03_继承
- leetcode 201:Bitwise AND of Numbers Range
- 计算机为什么要用补码
- Java核心API -- 14(Socket)
- 2015多校联合第二场5308I Wanna Become A 24-Point Master
- 第三方加载图片
- Reactor Pattern Explained