-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph4.java
113 lines (96 loc) · 3.27 KB
/
Graph4.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.*;
public class Graph4 {
static class Edge {
int src, dest;
public Edge(int s, int d) {
this.src = s;
this.dest = d;
}
}
static void createGraph(ArrayList<Edge> graph[]) {
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
// for vertex =0
graph[0].add(new Edge(0, 1));
// for vertex =1
graph[1].add(new Edge(1, 0));
graph[1].add(new Edge(1, 2));
graph[1].add(new Edge(1, 3));
// for vertex =2
graph[2].add(new Edge(2, 1));
graph[2].add(new Edge(2, 3));
graph[2].add(new Edge(2, 4));
// for vertex=3
graph[3].add(new Edge(3, 1));
graph[3].add(new Edge(3, 2));
// for vertex =4
graph[4].add(new Edge(4, 2));
// accessing neighbors of vertex 2
for (int i = 0; i < graph[2].size(); i++) {
Edge e = graph[2].get(i);
System.out.println(e.dest);
}
}
// CYCLE DETECTION
// In Undirected Graph time comp =O(v+e)
public static boolean detectCycle(ArrayList<Edge>[] graph) {
boolean vis[] = new boolean[graph.length];
for (int i = 0; i < graph.length; i++) {
if (!vis[i]) {
if (detectCycleUtil(graph, vis, i, -1)) {
return true;
}
}
}
return false;
}
public static boolean detectCycleUtil(ArrayList<Edge>[] graph, boolean vis[], int curr, int par) {
vis[curr] = true;
for (int i = 0; i < graph[curr].size(); i++) {
Edge e = graph[curr].get(i);
if (!vis[e.dest]) {
if (detectCycleUtil(graph, vis, e.dest, curr)) {
return true;
}
} else if (vis[e.dest] && e.dest != par) {
return true;
}
}
return false;
}
// In Directed Graph, time complexity = O(V+E)
public static boolean isCycle(ArrayList<Edge>[] graph) {
boolean vis[] = new boolean[graph.length];
boolean stack[] = new boolean[graph.length];
for (int i = 0; i < graph.length; i++) {
if (!vis[i]) {
if (isCycleUtil(graph, i, vis, stack)) {
return true;
}
}
}
return false;
}
public static boolean isCycleUtil(ArrayList<Edge>[] graph, int curr, boolean vis[], boolean stack[]) {
vis[curr] = true;
stack[curr] = true;
for (int i = 0; i < graph[curr].size(); i++) {
Edge e = graph[curr].get(i);
if (stack[e.dest]) {// cycle exists is neighbor already exists in the stack
return true;
}
if (!vis[e.dest] && isCycleUtil(graph, e.dest, vis, stack)) { // is neighbor is not present, check further
// and if a cycle is detected, return true.
return true;
}
}
return false;
}
public static void main(String[] args) {
int v = 5;
ArrayList<Edge> graph[] = new ArrayList[v];
createGraph(graph);
System.out.println(isCycle(graph));
}
}