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