[LintCode] Connecting Graph

Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning.

You need to support the following method:

1. connect(a, b), add an edge to connect node a and node b. 2.query(a, b)`, check if two nodes are connected

Example

5 // n = 5
query(1, 2) return false
connect(1, 2)
query(1, 3) return false
connect(2, 4)
query(1, 4) return true

Solution 1. BFS, O(1) connect, O(V) query, O(V + E) space

 1 public class ConnectingGraph {
 2     private ArrayList<HashSet<Integer>> lists = null;
 3     public ConnectingGraph(int n) {
 4         // initialize your data structure here.
 5         lists = new ArrayList<HashSet<Integer>>(n);
 6         for(int i = 0; i < n; i++){
 7             lists.add(new HashSet<Integer>());
 8         }
 9     }
10
11     public void connect(int a, int b) {
12         // Write your code here
13         lists.get(a - 1).add(b - 1);
14         lists.get(b - 1).add(a - 1);
15     }
16
17     public boolean query(int a, int b) {
18         // Write your code here
19         return bfs(a - 1, b - 1);
20     }
21
22     private boolean bfs(int source, int target){
23         Queue<Integer> queue = new LinkedList<Integer>();
24         HashSet<Integer> visited = new HashSet<Integer>();
25         queue.add(source);
26         visited.add(source);
27
28         while(!queue.isEmpty()){
29             int curr = queue.poll();
30             for(Integer i : lists.get(curr)){
31                 if(!visited.contains(i)){
32                     if(i == target){
33                         return true;
34                     }
35                     queue.add(i);
36                     visited.add(i);
37                 }
38             }
39         }
40         return false;
41     }
42 }

Solution 2. Union Find, O(1) connect and query on average, O(V) space(not storing edge information)

 1 class UnionFind {
 2     private int[] father = null;
 3     public UnionFind(int n){
 4         father = new int[n];
 5         for(int i = 0; i < n; i++){
 6             father[i] = i;
 7         }
 8     }
 9     public int find(int x){
10         if(father[x] == x){
11             return x;
12         }
13         return father[x] = find(father[x]);
14     }
15     public void connect(int a, int b){
16         int root_a = find(a);
17         int root_b = find(b);
18         if(root_a != root_b){
19             father[root_a] = root_b;
20         }
21     }
22 }
23 public class ConnectingGraph {
24     private UnionFind uf = null;
25     public ConnectingGraph(int n) {
26         // initialize your data structure here.
27         uf = new UnionFind(n);
28     }
29
30     public void connect(int a, int b) {
31         uf.connect(a - 1, b - 1);
32     }
33
34     public boolean query(int a, int b) {
35         return uf.find(a - 1) == uf.find(b - 1);
36     }
37 }

Related Problems

Connecting Graph II

Connecting Graph III

Graph Valid Tree

Surrounded Regions

Find the Weakly Connected Component in Directed Graph

Minimum Spanning Tree

Number of Islands II

				
时间: 2024-10-12 11:56:03

[LintCode] Connecting Graph的相关文章

[LintCode] Connecting Graph III

Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning. You need to support the following method:1. connect(a, b), an edge to connect node a and node b2. query(), Returns the number of connected component in the gra

[LintCode] Clone Graph

Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's undirected graph serialization: Nodes are labeled uniquely. We use # as a separator for each node, and , as a separator for node label an

GYM - 100814 C.Connecting Graph

题意: 初始有n个点,m次操作.每次操作加一条边或者询问两个点第一次连通的时刻(若不连通输出-1). 题解: 用并查集维护每个点所在连通块的根.对于每次加边,暴力的更新新的根. 每次将2个块合并时,将小的块并向大的块.这么合并使得每个点的根最多更新log2n次,并储存每次更新信息(更新时刻以及新的根). 对于每一次询问,二分两个点第一次连通的时刻.对于每一个二分的时刻,求的是两点的根是否相同. 由于存储过了每个点根的更新信息,所以再用二分求出他这个时刻的根. #include <bits/std

[LintCode] Surrounded Regions

Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O''s into 'X''s in that surrounded region. Have you met this question in a real interview? Yes Example X X X X X O O X X X O X X O X

【Lintcode】137.Clone Graph

题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. How we serialize an undirected graph: Nodes are labeled uniquely. We use # as a separator for each node, and , as a separator for node label and each

[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

Lintcode: Route Between Two Nodes in Graph

Given a directed graph, design an algorithm to find out whether there is a route between two nodes. Have you met this question in a real interview? Yes Example Given graph: A----->B----->C \ | \ | \ | \ v ->D----->E for s = B and t = E, return