forked from striver79/StriversGraphSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topoSortJava
85 lines (74 loc) · 2.51 KB
/
topoSortJava
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
import java.lang.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
String st[] = read.readLine().trim().split("\\s+");
int edg = Integer.parseInt(st[0]);
int nov = Integer.parseInt(st[1]);
for (int i = 0; i < nov + 1; i++)
list.add(i, new ArrayList<Integer>());
int p = 0;
for (int i = 1; i <= edg; i++) {
String s[] = read.readLine().trim().split("\\s+");
int u = Integer.parseInt(s[0]);
int v = Integer.parseInt(s[1]);
list.get(u).add(v);
}
int[] res = new Solution().topoSort(nov, list);
if (check(list, nov, res) == true)
System.out.println("1");
else
System.out.println("0");
}
}
static boolean check(ArrayList<ArrayList<Integer>> list, int V, int[] res) {
int[] map = new int[V];
for (int i = 0; i < V; i++) {
map[res[i]] = i;
}
for (int i = 0; i < V; i++) {
for (int v : list.get(i)) {
if (map[i] > map[v]) return false;
}
}
return true;
}
}
// } Driver Code Ends
/*Complete the function below*/
/*
ArrayList<ArrayList<>Integer>adj: to represent graph containing 'N' vertices
and edges between them
N: represent number of vertices
*/
class Solution {
static void findTopoSort(int node, int vis[], ArrayList<ArrayList<Integer>> adj, Stack<Integer> st) {
vis[node] = 1;
for(Integer it: adj.get(node)) {
if(vis[it] == 0) {
findTopoSort(it, vis, adj, st);
}
}
st.push(node);
}
static int[] topoSort(int N, ArrayList<ArrayList<Integer>> adj) {
Stack<Integer> st = new Stack<Integer>();
int vis[] = new int[N];
for(int i = 0;i<N;i++) {
if(vis[i] == 0) {
findTopoSort(i, vis, adj, st);
}
}
int topo[] = new int[N];
int ind = 0;
while(!st.isEmpty()) {
topo[ind++] = st.pop();
}
// for(int i = 0;i<N;i++) System.out.println(topo[i] + " ");
return topo;
}
}