-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathTopological Sort
67 lines (60 loc) · 1.85 KB
/
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
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
int noOfVertices = 5;
int[][] adj=new int[][]{
{0,1,1,0,1},
{0,0,0,1,0},
{0,0,0,1,0},
{0,0,0,0,0},
{0,0,0,0,0}
};
topologicalSort(noOfVertices,adj);
//Graph with Cycle
noOfVertices = 6;
adj=new int[][]{
{0,1,1,0,1,0},
{0,0,0,1,0,0},
{0,0,0,1,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,1},
{0,0,0,0,1,0}
};
topologicalSort(noOfVertices,adj);
}
static void topologicalSort(int noOfVertices,int[][] adj){
int[] indegree=new int[noOfVertices];
for(int i=0;i<noOfVertices;i++){
for(int j=0;j<noOfVertices;j++){
if(adj[i][j]==1){
indegree[j]++;
}
}
}
System.out.println("In-degree Array : "+Arrays.toString(indegree));
Queue<Integer> q=new LinkedList<>();
for(int i=0;i<noOfVertices;i++){
if(indegree[i]==0){
q.add(i);
}
}
int topologicalOrder=0;
System.out.println("Topological Ordering");
while(!q.isEmpty()){
int vertex=q.remove();
System.out.println(vertex+" -> "+(char)(vertex + 'A'));
topologicalOrder++;
for(int i=0;i<noOfVertices;i++){
if(adj[vertex][i]==1){
indegree[i]--;
if(indegree[i]==0){
q.add(i);
}
}
}
}
if(topologicalOrder!=noOfVertices){
System.out.println("Graph has Cycle");
}
}
}