-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCheckIsTree.java
More file actions
67 lines (50 loc) · 1.5 KB
/
Copy pathCheckIsTree.java
File metadata and controls
67 lines (50 loc) · 1.5 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
/*
* Problem statement:
* Given an undirected graph, check if is is a tree or not. In other words,
* check if given undirected graph is a Acyclic Connected Graph or not.
*
* Problem link:
* https://www.techiedelight.com/determine-undirected-graph-tree-acyclic-connected-graph/
*/
package Graph;
import java.util.Arrays;
import java.util.List;
public class CheckIsTree {
private static boolean DFSUtil(Graph graph, int source, int parent, boolean[] visited) {
visited[source] = true;
for (Edge edge : graph.adjacencyList.get(source)) {
int destination = edge.destination;
if (!visited[destination]) {
if (!DFSUtil(graph, destination, source, visited)) {
return false;
}
} else if (destination != parent) {
return false;
}
}
return true;
}
public static void main(String args[]) {
List<Edge> edges = Arrays.asList(
new Edge(0, 1), new Edge(1, 2), new Edge(2, 3),
new Edge(3, 4), new Edge(4, 5), new Edge(5, 0)
// edge (5->0) introduces a cycle in the graph
);
// Number of vertices in the graph
final int N = 6;
// construct graph
Graph graph = new Graph(edges, N);
boolean[] visited = new boolean[N];
boolean isTree = DFSUtil(graph, 0, -1, visited);
for (int i = 0; i < N; ++i) {
if (!visited[i]) {
isTree = false;
}
}
if (isTree) {
System.out.println("Graph is tree");
} else {
System.out.println("Graph is not a tree");
}
}
}