-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cycle.java
96 lines (72 loc) · 2.04 KB
/
Cycle.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
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Cycle{
public static class Pair{
int dest ;
int distance ;
public Pair(int dest , int distance){
this.dest = dest;
this.distance = distance;
}
public int getFirst(){
return dest;
}
public int getSecond(){
return distance;
}
}
HashMap<Integer , List<Pair>> adj = new HashMap<>();
public void addedge(int src ,int dest , int distance){
adj.putIfAbsent(src , new LinkedList<>());
adj.putIfAbsent(dest , new LinkedList<>());
adj.get(src).add(new Pair(dest , distance));
adj.get(dest).add(new Pair(src , distance));
}
public boolean dfs(int node , boolean vis[],int parent){
vis[node] = true;
for(Pair it : adj.get(node)){
int curr = it.getFirst();
if(!vis[curr]){
if(dfs(curr, vis, node)){
return true;
}
}
else{
if(curr != parent){
return true;
}
}
}
return false;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
Cycle c = new Cycle();
for(int i = 0; i < m; i++){
int src = sc.nextInt();
int dest = sc.nextInt();
int dist = sc.nextInt();
c.addedge(src-1, dest-1, dist);
}
boolean vis[] = new boolean[n];
boolean flag = false;
int parent = -1;
for(int i = 1; i <= n; i++){
if(!vis[i]){
if(c.dfs(i,vis,parent)){
flag = true;
break;
}
}
}
if(flag){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}