Connected Component in Undirected Graph

Description

Find connected component in undirected graph.

Each node in the graph contains a label and a list of its neighbors.

(A connected 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.)

You need return a list of label set.

Nodes in a connected component should sort by label in ascending order. Different connected components can be in any order.

Clarification

Learn more about representation of graphs

Example

Example 1:

Input: {1,2,4#2,1,4#3,5#4,1,2#5,3}
Output: [[1,2,4],[3,5]]
Explanation:

  1------2  3
   \     |  |
    \    |  |
     \   |  |
      \  |  |
        4   5

Example 2:

Input: {1,2#2,1}
Output: [[1,2]]
Explanation:

  1--2思路:无向图连通块, 可以使用BFS或者并查集union find求解 .
/**
 * Definition for Undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */

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(List<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());
    }
}

  

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078607.html

时间: 2024-07-30 18:58:19

Connected Component in Undirected Graph的相关文章

HDU 5333 Undirected Graph LCT+BIT

链接 Undirected Graph Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 184    Accepted Submission(s): 38 Problem Description As we know, Rikka is poor at math. Yuta is worrying about this situatio

[LintCode] Find the Connected Component in the Undirected Graph

Find the Connected Component in the Undirected Graph 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 i

lintcode 容易题:Find the Connected Component in the Undirected Graph 找出无向图汇总的相连要素

题目: 找出无向图汇总的相连要素 请找出无向图中相连要素的个数. 图中的每个节点包含其邻居的 1 个标签和 1 个列表.(一个无向图的相连节点(或节点)是一个子图,其中任意两个顶点通过路径相连,且不与超级图中的其它顶点相连.) 样例 给定图: A------B C \ | | \ | | \ | | \ | | D E 返回 {A,B,D}, {C,E}.其中有 2 个相连的元素,即{A,B,D}, {C,E} 解题: 广度优先+递归,写不出来,程序来源 Java程序: /** * Defini

[LintCode] Find the Weak Connected Component in the Directed Graph

Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.) Exam

Number of Connected Components in an Undirected Graph -- LeetCode

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: 0 3 | | 1 --- 2 4 Given n = 5 and edges = [[0, 1], [1,

LeetCode-Number of Connected Components in an Undirected Graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: 0 3 | | 1 --- 2 4 Given n = 5 and edges = [[0, 1], [1,

[Swift]LeetCode323. 无向图中的连通区域的个数 $ Number of Connected Components in an Undirected Graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: 0          3 |          | 1 --- 2    4 Given n = 5 and

Find the Weak Connected Component in the Directed Graph

Description Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a weak connected component of a directed graph is a maximum subgraph in which any two vertices are conne

普林斯顿《算法II》第一周学习笔记 Undirected Graph

普林斯顿的算法课是Cousera上评价挺高的一门课,课程的教学语言用的是java,课程中的算法都会被封装成类的形式,对于建立各个算法的知识结构来说还是很有好处的. 第一周的内容是Undirected Graph, 图的存储形式分为adjacency matrix(邻接矩阵)和 adjacency list(邻接表),前者对于可以以O(1)的复杂度查找两个节点是否有边,后的优势在于面对sparse maxtrix(稀疏矩阵)时可以存储很多空间. Depth-first search & Bread