-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.java
77 lines (67 loc) · 2.09 KB
/
App.java
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
package Graph.Question16;
/*
- Each node has exactly one parent(except root, having 0 parent)
- There are no cycles
- Graph is connected
or use BFS/DFS to check all above in one go
*/
public class App {
private static boolean dfsUtil(Graph graph, boolean[] visited, int source) {
visited[source] = true;
boolean flag = true;
for (int nbr: graph.getAdjList()[source]) {
if (!visited[nbr]) {
flag = flag & dfsUtil(graph, visited, nbr);
} else {
return false;
}
}
return flag;
}
private static int getRoot(Graph graph) {
boolean[] visited = new boolean[graph.getVertices()];
for (int i=0; i<graph.getVertices(); i++) {
for (int nbr: graph.getAdjList()[i]) {
visited[nbr] = true;
}
}
for (int i=0; i<visited.length; i++) {
if (!visited[i])
return i;
}
return -1;
}
public static boolean isTree(Graph graph) {
boolean[] visited = new boolean[graph.getVertices()];
int root = getRoot(graph);
System.out.println("Root : " + root);
if (root == -1)
return false;
boolean res = dfsUtil(graph, visited, root);
for (int i=0; i< graph.getVertices(); i++) {
if (!visited[i])
return false;
}
return res;
}
public static void main(String[] args) {
Graph graph1 = new Graph(5);
graph1.addEdge(0,1);
graph1.addEdge(0,2);
graph1.addEdge(0,3);
graph1.addEdge(3,4);
System.out.println("isTree : " + isTree(graph1));
Graph graph2 = new Graph(4);
graph2.addEdge(0,1);
graph2.addEdge(0,2);
graph2.addEdge(0,3);
graph2.addEdge(3,2);
System.out.println("isTree : " + isTree(graph2));
Graph graph3 = new Graph(6);
graph3.addEdge(0,1);
graph3.addEdge(0,2);
graph3.addEdge(0,3);
graph3.addEdge(4,5);
System.out.println("isTree : " + isTree(graph3));
}
}