-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphTreeOrNot.java
More file actions
56 lines (46 loc) · 1.44 KB
/
GraphTreeOrNot.java
File metadata and controls
56 lines (46 loc) · 1.44 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
package Trees;
import java.util.*;
public class GraphTreeOrNot {
public static void main(String[] args) {
Graph.initGraph(5);
Graph.addEdge(1, 0);
Graph.addEdge(0, 2);
Graph.addEdge(0, 3);
Graph.addEdge(3, 4);
if (Graph.isTree())
System.out.println("Graph is Tree");
else
System.out.println("Graph is not Tree");
}
static class Graph {
public static int V;
public static int E;
public static ArrayList<ArrayList<Integer>> adj;
public static void initGraph(int V) {
Graph.V = V;
E = 0;
adj = new ArrayList<>(V);
for (int i = 0; i < V; i++)
adj.add(new ArrayList<>());
}
static void dfsTraversal(int v, boolean[] visited, int parent) {
visited[v] = true;
for (int i : adj.get(v)) if (!visited[i]) dfsTraversal(i, visited, v);
}
public static void addEdge(int v, int w) {
E++;
adj.get(w).add(v);
adj.get(v).add(w);
}
public static boolean isConnected() {
boolean[] visited = new boolean[V];
dfsTraversal(0, visited, -1);
for (int u = 0; u < V; u++)
if (!visited[u]) return false;
return true;
}
public static boolean isTree() {
return isConnected() && E == V - 1;
}
}
}