-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCyclicGraph.java
86 lines (73 loc) · 2.2 KB
/
CyclicGraph.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
/*
Name: Is Graph Cyclic
Source: PepCoding
Link: https://www.pepcoding.com/resources/online-java-foundation/graphs/is-cyclic-official/ojquestion
Statement: You are required to find and print if the graph is cyclic.
*/
import java.io.*;
import java.util.*;
public class CyclicGraph {
static class Edge {
int src;
int nbr;
int wt;
Edge(int src, int nbr, int wt) {
this.src = src;
this.nbr = nbr;
this.wt = wt;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vtces = Integer.parseInt(br.readLine());
ArrayList < Edge > [] graph = new ArrayList[vtces];
for (int i = 0; i < vtces; i++) {
graph[i] = new ArrayList < > ();
}
int edges = Integer.parseInt(br.readLine());
for (int i = 0; i < edges; i++) {
String[] parts = br.readLine().split(" ");
int v1 = Integer.parseInt(parts[0]);
int v2 = Integer.parseInt(parts[1]);
int wt = Integer.parseInt(parts[2]);
graph[v1].add(new Edge(v1, v2, wt));
graph[v2].add(new Edge(v2, v1, wt));
}
boolean check = false;
boolean [] visited = new boolean[vtces];
for(int i=0; i<vtces; i++)
{
if(!visited[i])
{
check = isCyclic(i, visited, graph);
if(check)
{
break;
}
}
}
System.out.println(check);
}
public static boolean isCyclic(int src, boolean [] visited, ArrayList < Edge > [] graph)
{
ArrayDeque<Integer> que = new ArrayDeque<>();
que.add(src);
while(que.size()>0)
{
int top = que.remove();
if(visited[top])
{
return true;
}
visited[top] = true;
for(Edge edge: graph[top] )
{
if(!visited[edge.nbr])
{
que.add(edge.nbr);
}
}
}
return false;
}
}