【LintCode】在无向图中找出各极大连通子图 Find the Connected Component in the Undirected Graph
2015-08-16 15:01
513 查看
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.)
(lintcode上这道题的翻译有点问题。)
Example
Given graph:
Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}
(lintcode上这道题的翻译有点问题。)
Example
Given graph:
Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}
//广度优先搜索 /** * Definition for Undirected graph. * class UndirectedGraphNode { * int label; * ArrayList<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { * label = x; * neighbors = new ArrayList<UndirectedGraphNode>(); * } * }; */ public class Solution { /** * @param nodes a array of Undirected graph node * @return a connected set of a Undirected graph */ public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) { List<List<Integer>> resultSet = new LinkedList<List<Integer>>(); Set<Integer> visited = new HashSet<Integer>(); for(int i = 0; i < nodes.size(); i++) { if(!visited.contains(nodes.get(i).label)) {//若该节点未被访问过则加入队列,开始访问其邻居节点 List<Integer> list = new ArrayList<Integer>(); Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); queue.add(nodes.get(i)); list.add(nodes.get(i).label); visited.add(nodes.get(i).label); while(!queue.isEmpty()) {//将该节点未访问过的邻居节点加入队列 UndirectedGraphNode node = queue.poll(); for(int j = 0; j < node.neighbors.size(); j++) { UndirectedGraphNode nodeNei = node.neighbors.get(j); if(!visited.contains(nodeNei.label)) { queue.add(nodeNei); list.add(nodeNei.label); visited.add(nodeNei.label); } } } Collections.sort(list);//排序 resultSet.add(list); } } return resultSet; } }
相关文章推荐
- SpringMVC与mysql进行登录验证
- Java-高效地使用Exception-实践
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree
- redhat6 搭建vsftp
- HDU 4956 Poor Hanamichi(暴力)——BestCoder Round #5
- python操作xml文件详细介绍
- Unity 5 音效二 AudioMixer
- HDU 2099
- jQuery基础----18jQuery遍历之向上遍历
- 华为OJ(将真分数分解为埃及分数)
- 架构设计中的6种常见安全误区
- iOS调用系统通讯录获取姓名电话号码(转)
- ( 笔试题)只出现一次的数
- 三 HDU 2097
- jQuery基础----17jQuery遍历之向下遍历
- 一步步优化JVM五:优化延迟或者响应时间(1)
- 上传文件被nginx全部缓存的问题
- Uva 10341 Solve It(数论)
- jQuery基础----16jQuery CSS-jQuery盒子模型
- 多线程编程的资源争用问题