您的位置:首页 > 其它

【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}

//广度优先搜索
/**
* 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: