-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRootVertex.java
More file actions
108 lines (77 loc) · 2.22 KB
/
RootVertex.java
File metadata and controls
108 lines (77 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.*;
import java.io.*;
// Find the root vertex of the given graph
// Setting up the edges
class Edge{
int src,dest;
public Edge(int source, int dest){
this.src = source;
this.dest = dest;
}
}
// Class for initializing the graph
class Graph{
List<List<Integer>> list;
public Graph(List<Edge> edges, int size){
list = new ArrayList<>();
for(int i=0;i<size; i++){
list.add(new ArrayList<>());
}
for(Edge e: edges){
list.get(e.src).add(e.dest);
}
}
}
public class RootVertex {
static ArrayList<Integer> visited;
// Dfs to all the nodes to check if all the nodes exists in the current path
public static void dfs(Graph graph, int currNode){
if(visited.contains(currNode)) return;
visited.add(currNode);
for(int child: graph.list.get(currNode)){
dfs(graph, child);
}
}
// Helper function to initiate the dfs
public static int findRoot(Graph graph, int nodes){
for(int currRoot=0; currRoot<nodes; currRoot++){
visited = new ArrayList<>();
dfs(graph, currRoot);
// check if all the nodes are visited in the current iteration
// if all are visited then current node is the root node
if(visited.size() == nodes) return currRoot;
}
return -1;
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int nodes,root,edges;
ArrayList<Edge> edgeList = new ArrayList<>();
System.out.println("Enter number of nodes");
nodes = scan.nextInt();
System.out.println("Enter number of edges");
edges = scan.nextInt();
for(int i=0; i<edges; i++){
edgeList.add(new Edge(scan.nextInt(), scan.nextInt()));
}
scan.close();
Graph graph = new Graph(edgeList, nodes);
root = findRoot(graph, nodes);
if(root == -1) System.out.println("Root vertex does not exists");
else System.out.println("Root Vertex: " + root);
}
}
/*
Enter number of nodes
6
Enter number of edges
7
0 1
1 2
2 3
3 0
4 3
4 5
5 0
Root Vertex: 4
*/