lintcode431- Connected Component in Undirected Graph- medium

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.)

 Notice

Each connected component should sort by label.

Example

Given graph:

A------B  C
      |  | 
      |  |
      |  |
      |  |
      D   E

Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}

 

public List<List<Integer>> connectedSet(List<UndirectedGraphNode> nodes)

算法:for循环每个点,如果没被访问过,就开始做BFS产生新的List,加到List<List>里面。BFS做的内容就是最简单的加label,遍历邻居。

数据结构:Queue+Set标配 (这题set两个地方用到,一个是主函数for循环检查要去BFS不,一个是子函数BFS里查要加进queue不),。

细节:给List排序的函数是Collections.sort(list);

/**
 * 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(List<UndirectedGraphNode> nodes) {
        // write your code here
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (nodes == null || nodes.size() == 0) {
            return result;
        }
        
        Set<UndirectedGraphNode> globalSet = new HashSet<UndirectedGraphNode>();
        for (UndirectedGraphNode node : nodes) {
            if (globalSet.contains(node)) {
                continue;
            }
            List<Integer> list = bfs(node, globalSet);
            result.add(list);
        }
        return result;
        
    }
    
    private List<Integer> bfs(UndirectedGraphNode node, Set<UndirectedGraphNode> globalSet) {
        List<Integer> result = new ArrayList<Integer>();
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        // 其实冗余了,不需要再来个局部的set,用全局的就够了,因为某一个点被加进去过了就不可能存在在另一个团里被加第二次了。
        // Set<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
        
        queue.offer(node);
        globalSet.add(node);
        while (!queue.isEmpty()) {
            UndirectedGraphNode crt = queue.poll();
            result.add(crt.label);
            for (UndirectedGraphNode neighbor : crt.neighbors) {
                if (!globalSet.contains(neighbor)) {
                    queue.offer(neighbor);
                    globalSet.add(neighbor);
                }
            }
        }
        Collections.sort(result);
        return result;
    }
    
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7760579.html