-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.java (topological_sort)
74 lines (66 loc) · 1.52 KB
/
Graph.java (topological_sort)
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
/*
*
* @author shivam
*/
import java.util.*;
class Graph{
public int v;
public LinkedList<Integer> array[]; //array
Graph(int v)
{
System.out.println("const");
int V=v ;
array = new LinkedList[V];
for(int i=0;i<V;i++)
{
array[i]= new LinkedList<Integer>(V);
}
}
void addEdge(int src,int dest)
{
array[src].addLast(dest);
}
public void topological_sort_untill(int v,boolean visited[],Stack stack)
{
visited[v]=true;
Iterator<Integer> itr = array[v].iterator();
while(itr.next()!=null)
{
int i=itr.next();
topological_sort_untill(i,visited,stack);
}
stack.push(v);
}
public void topological_sort()
{
Stack stack= new Stack();
boolean visited[]= new boolean[v];
for(int i=0;i<v;i++)
visited[i]=false;
for(int i=0;i<v;i++)
{
if(visited[i]==false)
{
topological_sort_untill(i,visited,stack);
}
}
while(!stack.isEmpty())
System.out.println(stack.pop()+"->");
}
public static void main(String[] args) {
int no_of_vertex=5;
Graph graph= new Graph(no_of_vertex);
System.out.println("hello main");
try{ graph.addEdge(5, 2);
graph.addEdge(5, 0);
graph.addEdge(4, 0);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 1);
graph.topological_sort();
}catch(Exception e)
{
System.out.println("e.printStackTrace()");
}
}
}