题目:
代码:
import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int N = cin.nextInt();
boolean V[] = new boolean[N];
for (int i=0;i<N;i++){
V[i] = false;
}
int indegree[] = new int[N];
ArrayList<Integer> A[] = new ArrayList[N];
for (int i=0;i<N;i++){
A[i] = new ArrayList<>();
}
int M = cin.nextInt();
for (int i=0;i<M;i++){
int s = cin.nextInt();
int t = cin.nextInt();
indegree[t]++;
A[s].add(t);
}
LinkedList<Integer> out = myTopologicalSort(V, indegree, N, A);
for (int element : out){
System.out.println(element);
}
}
public static LinkedList<Integer> myTopologicalSort(boolean[] V, int[] indegree, int n, ArrayList<Integer> A[]){
LinkedList<Integer> out = new LinkedList<>();
String mode = "dfs";
if(mode.equals("bfs")){
for (int u=0;u<n;u++){
if(indegree[u]==0 && !V[u]){
out = bfs(u, V, indegree, out, A);//对于所有节点中的每一个节点运用bfs算法
}
}
}else if(mode.equals("dfs")){
for (int s = 0; s <n; s++){
if(!V[s]){
out = dfs(s, V, out, A);
}
}
Collections.reverse(out);
}
return out;
}
public static LinkedList<Integer> dfs(int u, boolean[] V, LinkedList<Integer> out, ArrayList<Integer> A[]){
V[u] = true;
for (int i = 0; i<A[u].size(); i++){
int v = A[u].get(i);//u的邻接点
if(!V[v]){
dfs(v, V, out, A);
}
}
out.add(u);
return out;
}
public static LinkedList<Integer> bfs(int s, boolean[] V, int[] indegree, LinkedList<Integer> out, ArrayList<Integer> A[]){
Queue<Integer> Q;
Q = new ArrayDeque();
//将当前节点设为处理中状态
Q.add(s);
V[s] = true;
//只要Q队列不为空就执行循环操作,广度搜索
while(Q.size()!=0){
int u;
//只有队头元素的入度为0时,才可以将其添加至out
u = Q.remove();
V[u] = true;
//删除Q的队头元素,并将队头元素赋给out
out.add(u);
//对于第u个节点的所有出度
for (int i=0;i<A[u].size();i++){
int v = A[u].get(i);//u的邻接点
indegree[v]--;
//如果v的入度为0且还没有被处理过
if(indegree[v]==0 && !V[v]){
V[v] = true;
Q.add(v);
}
}
}
return out;
}
}
输入:
6 6
0 1
1 2
3 1
3 4
4 5
5 2
bfs输出:
0
3
1
4
5
2
dfs输出:
3
4
5
0
1
2