【LintCode】在无向图中找出各极大连通子图 Find the Connected Component in the Undirected Graph

来源:互联网 发布:面膜推荐知乎 编辑:程序博客网 时间:2024/06/05 14:26

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;    }}
0 0
原创粉丝点击