DFS partitioning connected components

Questions: given a graph where nodes have undirected neighbours, partition them into connected groups
Idea: Pretty much the same as the previous solution for directed neighbours. It does not really matter whether it is directed or not. Since I already give a UnionFind solution in the previous question. This one we use DFS. Note that this one cannot be used in the previous directed graph, this is because you cannot determine when to create a new group for the connected components.

Example

IN: 1 and 2, 1 and 3, 2 and 3, 4 and 5
OUT: 1,2,3 and 4,5

/**
 * 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) {
        Set<UndirectedGraphNode> visited = new HashSet();
        List<List<Integer>> res = new LinkedList();
        for(UndirectedGraphNode node : nodes) {
            if (visited.contains(node)) continue;
            List<Integer> curList = new LinkedList<>();
            collect(node, visited, curList);
            res.add(curList);
        }
        return res;
    }
    
    private void collect(UndirectedGraphNode host,
        Set<UndirectedGraphNode> visited,
        List<Integer> list) {
            if (!visited.contains(host)) {
                visited.add(host);
                list.add(host.label);
            }
            for(UndirectedGraphNode node: host.neighbors) {
                if (visited.contains(node)) continue;
                visited.add(node);
                list.add(node.label);
                collect(node, visited, list);
            } 
        }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容