[LintCode] Connected Component in 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 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.)

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}

 

Solution 1. BFS

Algorithm.

Iterate all nodes in the input graph and do the following.

1. For each unvisited graph node s, do a bfs starting from it and add all nodes that can be reached from s to a list as one connected component. Add each visited nodes to a global set that tracks which nodes have been visited.

2. Sort each connected component.

 

 1 /**
 2  * Definition for Undirected graph.
 3  * class UndirectedGraphNode {
 4  *     int label;
 5  *     ArrayList<UndirectedGraphNode> neighbors;
 6  *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 7  * };
 8  */
 9 
10 //Algorithm 1. bfs 
11 public class Solution {
12     public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
13         List<List<Integer>> results = new ArrayList<List<Integer>>();
14         if(nodes == null || nodes.size() == 0)
15         {
16             return results;
17         }
18         Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
19         //bfs on each node to get all the connected components
20         for(UndirectedGraphNode node : nodes)   
21         {
22             if(!visited.contains(node))
23             {
24                 bfs(node, visited, results);
25             }
26         }
27         return results;
28     }
29     private void bfs(UndirectedGraphNode node, 
30                     Set<UndirectedGraphNode> visited,
31                     List<List<Integer>> results)
32     {
33         ArrayList<Integer> comp = new ArrayList<Integer>();
34         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
35         queue.offer(node);
36         visited.add(node);
37         comp.add(node.label);
38         
39         while(!queue.isEmpty())
40         {
41             UndirectedGraphNode curr = queue.poll();
42             for(UndirectedGraphNode neighbor : curr.neighbors)
43             {
44                 if(!visited.contains(neighbor))
45                 {
46                     queue.offer(neighbor);
47                     visited.add(neighbor);
48                     comp.add(neighbor.label);
49                 }
50             }
51         }
52         Collections.sort(comp);
53         results.add(comp);
54     }
55 }

 

 

Solution 2. Union Find

Algorithm.

1. Add each node to a union find data structure and connect these nodes based on the graph edges. A hash map is better suited for the union find since the input graph nodes' labels do not necessarily starts from 0 and are not guranteed to be consecutive. 

2. Iterate through the uf and create a mapping bewteen a root label and its represented node labels. Sort each map value and add it to the final result.

 

 1 //Algorithm 2. Union Find
 2 public class Solution {
 3     class UnionFind {
 4         private HashMap<Integer, Integer> father = null;
 5         public UnionFind(HashSet<Integer> labels){
 6             father = new HashMap<Integer, Integer>();
 7             for(Integer i : labels){
 8                 father.put(i, i);
 9             }
10         }
11         public int find(int x){
12             int parent = father.get(x);
13             while(parent != father.get(parent)){
14                 parent = father.get(parent);
15             }
16             
17             //compress path
18             int next;
19             while(x != father.get(x)){
20                 next = father.get(x);
21                 father.put(x, parent);
22                 x = next;
23             }
24             return parent;
25         }
26         public void connect(int x, int y){
27             int root_x = find(x);
28             int root_y = find(y);
29             if(root_x != root_y){
30                 father.put(root_x, root_y);
31             }
32         }
33         
34     }
35     public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
36         List<List<Integer>> results = new ArrayList<List<Integer>>();
37         if(nodes == null || nodes.size() == 0){
38             return results;
39         }
40         //store all nodes' labels in a hash set
41         HashSet<Integer> nodeLabels = new HashSet<Integer>();
42         for(UndirectedGraphNode node : nodes){
43             nodeLabels.add(node.label);
44             for(UndirectedGraphNode neighbor : node.neighbors){
45                 nodeLabels.add(neighbor.label);
46             }
47         }
48         //connect all nodes based on the edges
49         UnionFind uf = new UnionFind(nodeLabels);
50         for(UndirectedGraphNode node : nodes){
51             for(UndirectedGraphNode neighbor : node.neighbors){
52                 uf.connect(node.label, neighbor.label);
53             }
54         }
55         getAllCC(nodeLabels, uf, results);
56         return results;
57     }
58     private void getAllCC(HashSet<Integer> nodeLabels, UnionFind uf, List<List<Integer>> results){
59         //key: root representative of each connected component
60         //value: connected component
61         HashMap<Integer, List<Integer>> cc = new HashMap<Integer, List<Integer>>();
62         for(int i : nodeLabels){
63             int root = uf.find(i);
64             if(!cc.containsKey(root)){
65                 cc.put(root, new ArrayList<Integer>());
66             }
67             cc.get(root).add(i);
68         }
69         //sort answers
70         for(List<Integer> comp : cc.values()){
71             Collections.sort(comp);
72             results.add(comp);
73         }
74     }
75 }

 

 

Related Problems

Graph Valid Tree

Find the Weak Connected Component in the Directed Graph

转载于:https://www.cnblogs.com/lz87/p/7496951.html

A-3 Linear Component 分数 25 作者 陈越 单位 浙江大学 A component of an undirected graph G is a maximum connected sub-graph of G. A linear component is a component that has a nonlinear structure property-- that is, each vertex in that component has exactly one or two previous vertex (except the first one), and one next vertex (except the last one). The size of a linear component is the number of edges plus vertices in the component. Now given an undirected graph, you are supposed to use assembly language find the largest size of its linear components. Input Specification: Each input file contains one test case, which first gives 2 positive integers: n (≤10 4 ), the number of vertices, and m (≤5n), the number of edges. Then m lines follow, each describes an edge in the form u v, where u and v are the indices of the two ends of the edge. The vertices are indexed from 1 to n. It is guaranteed that no duplicated edges are given. Output Specification: For each case, print in a line the number of vertices and the largest size of the linear components. Use variable dhjskycvi0 to store data. The numbers must be separated by a space. If there is no linear component, the maximum size is defined to be &minus;1. Sample Input 1: 14 11 1 2 2 3 3 1 4 5 6 5 6 7 8 7 9 10 11 12 11 13 11 14 Sample Output 1: 2 4 Sample Input 2: 4 4 1 2 2 3 3 4 4 2 Sample Output 2: 0 -1 代码长度限制 16 KB Java (javac) 时间限制 1100 ms 内存限制 512 MB Python (python3) 时间限制 500 ms 内存限制 256 MB 其他编译器 时间限制 400 ms 内存限制 64 MB 栈限制 8192 KB c++题解
07-23
内容概要:本文详细介绍了一个基于Java和Vue的联邦学习隐私保护推荐系统的设计与实现。系统采用联邦学习架构,使用户数据在本地完成模型训练,仅上传加密后的模型参数或梯度,通过中心服务器进行联邦平均聚合,从而实现数据隐私保护与协同建模的双重目标。项目涵盖完整的系统架构设计,包括本地模型训练、中心参数聚合、安全通信、前后端解耦、推荐算法插件化等模块,并结合差分隐私与同态加密等技术强化安全性。同时,系统通过Vue前端实现用户行为采集与个性化推荐展示,Java后端支撑高并发服务与日志处理,形成“本地训练—参数上传—全局聚合—模型下发—个性化微调”的完整闭环。文中还提供了关键模块的代码示例,如特征提取、模型聚合、加密上传等,增强了项目的可实施性与工程参考价值。 适合人群:具备一定Java和Vue开发基础,熟悉Spring Boot、RESTful API、分布式系统或机器学习相关技术,从事推荐系统、隐私计算或全栈开发方向的研发人员。 使用场景及目标:①学习联邦学习在推荐系统中的工程落地方法;②掌握隐私保护机制(如加密传输、差分隐私)与模型聚合技术的集成;③构建高安全、可扩展的分布式推荐系统原型;④实现前后端协同的个性化推荐闭环系统。 阅读建议:建议结合代码示例深入理解联邦学习流程,重点关注本地训练与全局聚合的协同逻辑,同时可基于项目架构进行算法替换与功能扩展,适用于科研验证与工业级系统原型开发。
源码来自:https://pan.quark.cn/s/a4b39357ea24 遗传算法 - 简书 遗传算法的理论是根据达尔文进化论而设计出来的算法: 人类是朝着好的方向(最优解)进化,进化过程中,会自动选择优良基因,淘汰劣等基因。 遗传算法(英语:genetic algorithm (GA) )是计算数学中用于解决最佳化的搜索算法,是进化算法的一种。 进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择、杂交等。 搜索算法的共同特征为: 首先组成一组候选解 依据某些适应性条件测算这些候选解的适应度 根据适应度保留某些候选解,放弃其他候选解 对保留的候选解进行某些操作,生成新的候选解 遗传算法流程 遗传算法的一般步骤 my_fitness函数 评估每条染色体所对应个体的适应度 升序排列适应度评估值,选出 前 parent_number 个 个体作为 待选 parent 种群(适应度函数的值越小越好) 从 待选 parent 种群 中随机选择 2 个个体作为父方和母方。 抽取父母双方的染色体,进行交叉,产生 2 个子代。 (交叉概率) 对子代(parent + 生成的 child)的染色体进行变异。 (变异概率) 重复3,4,5步骤,直到新种群(parentnumber + childnumber)的产生。 循环以上步骤直至找到满意的解。 名词解释 交叉概率:两个个体进行交配的概率。 例如,交配概率为0.8,则80%的“夫妻”会生育后代。 变异概率:所有的基因中发生变异的占总体的比例。 GA函数 适应度函数 适应度函数由解决的问题决定。 举一个平方和的例子。 简单的平方和问题 求函数的最小值,其中每个变量的取值区间都是 [-1, ...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值