-
Notifications
You must be signed in to change notification settings - Fork 0
/
Practice_2.java
129 lines (96 loc) · 2.94 KB
/
Practice_2.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package DisJoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Practice_2{
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 distance(){
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 void dfs(int start , boolean vis[] , ArrayList<Integer> ans){
vis[start] = true;
ans.add(start);
for(Pair it : adj.get(start)){
int node = it.getFirst();
if(!vis[node]){
dfs(node , vis , ans);
}
}
}
public boolean detect_cylce(int node , boolean vis[], int parent){
vis[node] = true;
for(Pair it : adj.get(node)){
int curr = it.getFirst();
if(!vis[it.getFirst()]){
detect_cylce(curr, vis, node);
}
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();
Practice_2 p = new Practice_2();
boolean vis[] = new boolean[n];
ArrayList<Integer> ans = new ArrayList<>();
for(int i = 0; i < m; i++){
int src = sc.nextInt();
int dest = sc.nextInt();
int distance = sc.nextInt();
p.addEdge(src,dest,distance);
}
p.dfs(0,vis,ans);
for(int i = 0; i < ans.size(); i++){
System.out.print(ans.get(i));
}
System.out.println();
Queue<Integer> q = new LinkedList<>();
q.offer(0);
boolean visited[] = new boolean[n];
ArrayList<Integer> ans2 = new ArrayList<>();
while(!q.isEmpty()){
int node = q.poll();
if(visited[node]){
continue;
}
visited[node] = true;
ans2.add(node);
for(Pair it : p.adj.get(node)){
int currnode = it.getFirst();
q.offer(currnode);
}
}
for(int i = 0; i < ans2.size(); i++){
System.out.print(ans2.get(i));
}
System.out.println();
boolean flag = p.detect_cylce(0, visited, -1);
System.out.println(flag);
}
}