import java util Stack public class TopologicalSort private Stack Inte

 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
import java.util.Stack;
public class TopologicalSort {
private Stack<Integer> stack;
public TopologicalSort() {
stack = new Stack<Integer>();
}
public int[] topological(int arr[][], int source) throws NullPointerException {
// 0 - белая вершина, 1 - серая вершина, 2 - черная вершина
int number_of_nodes = arr[source].length - 1;
int[] topological_sort = new int[number_of_nodes + 1];
int pos = 1;
int j;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty()) {
element = stack.peek();
while (i <= number_of_nodes) {
if (arr[element][i] == 1 && visited[i] == 1) {
if (stack.contains(i)) {
System.out.println("The graph contains circuit. Topological sort not possible.");
return null;
}
}
if (arr[element][i] == 1 && visited[i] == 0) {
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
continue;
}
i++;
}
j = stack.pop();
topological_sort[pos++] = j;
i = ++j;
}
return topological_sort;
}
}