-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoposort.java
More file actions
39 lines (31 loc) · 993 Bytes
/
toposort.java
File metadata and controls
39 lines (31 loc) · 993 Bytes
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
import java.util.ArrayList;
import java.util.Stack;
public class toposort {
static ArrayList<Integer> topologicalSort(ArrayList<ArrayList<Integer>> adj) {
// Your code here
int V=adj.size();
int visited[]=new int[V];
Stack<Integer> st=new Stack<Integer>();
for(int i=0;i<V;i++){
if(visited[i]==0){
dfs(i,visited,st,adj);
}
}
ArrayList<Integer> ans=new ArrayList<Integer>();
while(!st.isEmpty()){
int i=st.peek();
ans.add(i);
st.pop();
}
return ans;
}
static void dfs(int node,int visited[], Stack<Integer> st,ArrayList<ArrayList<Integer>> ad){
visited[node]=1;
for(int i:ad.get(node)){
if(visited[i]!=1){
dfs(i,visited,st,ad);
}
}
st.push(node);
}
}