This repository was archived by the owner on May 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycle.java
More file actions
82 lines (62 loc) · 1.68 KB
/
Cycle.java
File metadata and controls
82 lines (62 loc) · 1.68 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
import java.io.*;
import java.util.*;
class Cycle {
// Graph
static LinkedList<Integer>[] adj;
// Visited
static boolean[] visited;
// Check for cycles
static boolean hasCycle(int index) {
// Ever been here before?
if (visited[index])
return true;
// Mark as visited
visited[index] = true;
// DFS
for (Integer a : adj[index])
if (hasCycle(a))
return true;
// Found none
return false;
}
// Runner
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
// Get input file
File inputFile = new File("./input.txt");
// Open read stream
Scanner sc = new Scanner(inputFile);
// Vertices / Edges
int V = sc.nextInt();
int E = sc.nextInt();
// Set vertices
adj = new LinkedList[V + 1];
// Create vertices
for (int i = 1; i <= V; i++) {
adj[i] = new LinkedList<>();
}
// Create edges
for (int i = 0; i < E; i++) {
int f = sc.nextInt();
int t = sc.nextInt();
adj[f].add(t);
}
// Close read stream
sc.close();
// Exceptions
if (V == 0) {
System.out.println("Acyclic");
return;
}
// Checks for cycles
for (int i = 1; i <= V; i++) {
visited = new boolean[V + 1];
if (hasCycle(i)) {
System.out.println("The graph is cyclic!");
return;
}
}
// None?
System.out.println("The graph is acyclic!");
}
}