Skip to content

Instantly share code, notes, and snippets.

@gordinmitya
Created April 7, 2020 12:29
Show Gist options
  • Save gordinmitya/9c260f83affa0d96fca1cc9713419ef1 to your computer and use it in GitHub Desktop.
Save gordinmitya/9c260f83affa0d96fca1cc9713419ef1 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Topo {
private static final int WHITE = 0;
private static final int GRAY = 1;
private static final int BLACK = 2;
private static void dfs(int v, List<List<Integer>> edges, int[] state, List<Integer> sorting) {
state[v] = GRAY;
List<Integer> children = edges.get(v);
for (Integer child : children) {
if (state[child] == GRAY)
throw new RuntimeException(String.format("Loop from %d to %d", v, child));
if (state[child] == BLACK)
continue;
if (state[child] == WHITE)
dfs(child, edges, state, sorting);
}
state[v] = BLACK;
sorting.add(v);
}
private static List<Integer> topoSort(List<List<Integer>> edges, int N) {
List<Integer> sorting = new ArrayList<>(N);
int[] states = new int[N]; // all are white
for (int i = 0; i < N; i++) {
if (states[i] == WHITE)
dfs(i, edges, states, sorting);
}
return sorting;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int e = scanner.nextInt();
List<List<Integer>> edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
edges.add(new ArrayList<>());
}
for (int i = 0; i < e; i++) {
int from = scanner.nextInt() - 1;
int to = scanner.nextInt() - 1;
edges.get(from).add(to);
}
List<Integer> results = topoSort(edges, n);
for (int i = results.size() - 1; i >= 0; i--) {
System.out.format("%d ", results.get(i) + 1);
}
}
}
/*
n e
e lines with `from` `to`
5 5
1 2
1 3
2 3
4 3
4 5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment