431.找无向图的连通块

描述

找出无向图中所有的连通块。
图中的每个节点包含一个label属性和一个邻接点的列表。(一个无向图的�连通块是一个子图,其中任意两个顶点通过路径相连,且不与整个图中的其它顶点相连。)

注意事项

每个连通块内部应该按照label属性排序

说明

Learn more about representation of graphs

样例

给定图:

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

返回 {A,B,D}, {C,E}。其中有 2 个连通块,即{A,B,D}, {C,E}

注意事项

每个连通块内部应该按照label属性排序

思路

本题bfs的做法还是比较容易理解的,先给所有结点做一个false标记,然后用for循环遍历所有点标记为false的点,从一个点开始进行bfs找到所有能找到的点,将找到的点标记为true;结果加到数组排序

代码

  1. bfs
/**
 *  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) {
        List<List<Integer>> results = new ArrayList<>();
        Map<UndirectedGraphNode, Boolean> visited = new HashMap<>();
        
        if (nodes.size() == 0) {
            return results;
        }
        
        for (int i = 0; i < nodes.size(); i++) {
            visited.put(nodes.get(i), true);
        }
        
        for (int i = 0; i < nodes.size(); i++) {
            UndirectedGraphNode node = nodes.get(i);
            if (visited.get(node) == true) {
                bfs(node, visited, results);
            }
        }
        
        return results;
    }
    
    private void bfs(UndirectedGraphNode node, 
                     Map<UndirectedGraphNode, Boolean> visited, 
                     List<List<Integer>> results) {
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        List<Integer> level = new ArrayList<>();
        
        queue.offer(node);
        visited.put(node, false);
        while (!queue.isEmpty()) {
            UndirectedGraphNode head = queue.poll();
            level.add(head.label);
            for (UndirectedGraphNode neighbor : head.neighbors) {
                if (visited.get(neighbor) == true) {
                    queue.offer(neighbor);
                    visited.put(neighbor, false);
                }
            }
        }
        Collections.sort(level);
        results.add(level);
    }
}
  1. 并查集
public
class Solution {
    class UnionFind {
        HashMap<Integer, Integer> father = new HashMap<Integer, Integer>();
        UnionFind(HashSet<Integer> hashSet)
        {
            for (Integer now : hashSet) {
                father.put(now, now);
            }
        }
        int find(int x)
        {
            int parent = father.get(x);
            while (parent != father.get(parent)) {
                parent = father.get(parent);
            }
            return parent;
        }
        int compressed_find(int x)
        {
            int parent = father.get(x);
            while (parent != father.get(parent)) {
                parent = father.get(parent);
            }
            int next;
            while (x != father.get(x)) {
                next = father.get(x);
                father.put(x, parent);
                x = next;
            }
            return parent;
        }

        void union(int x, int y)
        {
            int fa_x = find(x);
            int fa_y = find(y);
            if (fa_x != fa_y)
                father.put(fa_x, fa_y);
        }
    }
    
    List<List<Integer> > print(HashSet<Integer> hashSet, UnionFind uf, int n) {
        List<List<Integer> > ans = new ArrayList<List<Integer> >();
        HashMap<Integer, List<Integer> > hashMap = new HashMap<Integer, List<Integer> >();
        for (int i : hashSet) {
            int fa = uf.find(i);
            if (!hashMap.containsKey(fa)) {
                hashMap.put(fa, new ArrayList<Integer>());
            }
            List<Integer> now = hashMap.get(fa);
            now.add(i);
            hashMap.put(fa, now);
        }
        for (List<Integer> now : hashMap.values()) {
            Collections.sort(now);
            ans.add(now);
        }
        return ans;
    }

public
    List<List<Integer> > connectedSet(ArrayList<UndirectedGraphNode> nodes)
    {
        // Write your code here

        HashSet<Integer> hashSet = new HashSet<Integer>();
        for (UndirectedGraphNode now : nodes) {
            hashSet.add(now.label);
            for (UndirectedGraphNode neighbour : now.neighbors) {
                hashSet.add(neighbour.label);
            }
        }
        UnionFind uf = new UnionFind(hashSet);

        for (UndirectedGraphNode now : nodes) {

            for (UndirectedGraphNode neighbour : now.neighbors) {
                int fnow = uf.find(now.label);
                int fneighbour = uf.find(neighbour.label);
                if (fnow != fneighbour) {
                    uf.union(now.label, neighbour.label);
                }
            }
        }

        return print(hashSet, uf, nodes.size());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 10,619评论 0 12
  • 第一章 绪论 什么是数据结构? 数据结构的定义:数据结构是相互之间存在一种或多种特定关系的数据元素的集合。 第二章...
    SeanCheney阅读 11,099评论 0 19
  • 图是一种比线性表和树更复杂的数据结构,在图中,结点之间的关系是任意的,任意两个数据元素之间都可能相关。图是一种多对...
    Alent阅读 6,887评论 1 22
  • 现实生活中有很大一类问题可以用简洁明了的图论语言来描述,可以转化为图论问题。 相关定义 图可以表示为G=(V, E...
    芥丶未央阅读 5,694评论 0 7
  • 本文介绍图的几种基本操作:BFS,DFS,求有向图连通分量的Tarjan算法以及拓扑排序。 图的表示 一张图是由若...
    maxkibble阅读 8,771评论 0 2