Skip to content

Commit 908fd84

Browse files
committed
Create TreeCheck.java
Added a Java program to check if an undirected graph is a tree using DFS and adjacency matrix. Verifies connectivity and absence of cycles.
1 parent a8ad162 commit 908fd84

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.thealgorithms.tree;
2+
3+
import java.util.Scanner;
4+
5+
class GraphTreeCheck {
6+
7+
private static final int MAX = 10;
8+
private int[][] adjMatrix = new int[MAX][MAX];
9+
private boolean[] visited = new boolean[MAX];
10+
private int nodes;
11+
12+
public static void main(String[] args) {
13+
Scanner in = new Scanner(System.in);
14+
GraphTreeCheck graph = new GraphTreeCheck();
15+
16+
System.out.print("Enter the number of nodes: ");
17+
graph.nodes = in.nextInt();
18+
19+
System.out.println("Enter the Adjacency Matrix (1 -> PATH, 0 -> NO PATH):");
20+
for (int i = 1; i <= graph.nodes; i++) {
21+
for (int j = 1; j <= graph.nodes; j++) {
22+
graph.adjMatrix[i][j] = in.nextInt();
23+
if (i == j) {
24+
graph.adjMatrix[i][j] = 0; // No self loops
25+
}
26+
}
27+
}
28+
29+
if (graph.isTree()) {
30+
System.out.println("The graph is a TREE.");
31+
} else {
32+
System.out.println("The graph is NOT a tree.");
33+
}
34+
}
35+
36+
public boolean isTree() {
37+
// Check for cycles using DFS
38+
if (hasCycle(1, -1)) {
39+
return false;
40+
}
41+
42+
// Check for connectivity
43+
for (int i = 1; i <= nodes; i++) {
44+
if (!visited[i]) {
45+
return false;
46+
}
47+
}
48+
49+
return true;
50+
}
51+
52+
private boolean hasCycle(int current, int parent) {
53+
visited[current] = true;
54+
55+
for (int neighbor = 1; neighbor <= nodes; neighbor++) {
56+
if (adjMatrix[current][neighbor] == 1) {
57+
if (!visited[neighbor]) {
58+
if (hasCycle(neighbor, current)) {
59+
return true;
60+
}
61+
} else if (neighbor != parent) {
62+
// Found a back edge indicating a cycle
63+
return true;
64+
}
65+
}
66+
}
67+
return false;
68+
}
69+
}

0 commit comments

Comments
 (0)