import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
*
5
3
1 3
2 3
2 4
5
8
1 4
1 2
2 4
2 3
4 3
4 5
3 5
4 1
5
8
1 4
1 2
2 4
2 3
4 3
4 5
3 5
4 2
5
7
1 4
1 2
2 4
2 3
4 3
4 5
3 5
*/
public class TopologicalSort {
static int maxn; // 顶点数
static int edgen; // 边数
static int[][] graph; // 图
static int[] indegree; // 每个点的入度
static int[] vstd; // 点的访问状态
static List<Integer> topo = new ArrayList<Integer>(); //结果
static boolean cyclic = false;
static void dfs(int u) {
if(cyclic) {
return;
}
vstd[u] = -1; // 正在搜索中
for (int i = 1; i < maxn && !cyclic; i++) {
if (graph[u][i] == 1) {
if(vstd[i] == -1) { // 正在搜索中的点被再次搜索,说明存在环
System.out.println("存在有向环");
cyclic = true;
return;
} else if(vstd[i] == 0) {
dfs(i);
}
}
}
topo.add(u);
vstd[u] = 1;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
maxn = scan.nextInt() + 1; //
edgen = scan.nextInt();
graph = new int[maxn][maxn];
indegree = new int[maxn];
vstd = new int[maxn];
for (int i = 0; i < edgen; i++) {
int u = scan.nextInt();
int v = scan.nextInt();
graph[u][v] = 1;
indegree[v]++;
}
scan.close();
List<Integer> zeroDegree = new ArrayList<Integer>();
for (int u = 1; u < maxn; u++) {
for (int v = 1; v < maxn; v++) {
// 从入度为0的顶点开始搜索
if (indegree[u] == 0 && graph[u][v] == 1) {
zeroDegree.add(u);
break;
}
}
}
if(zeroDegree.size() == 0) {
System.out.println("不存在入度为0的顶点,即存在闭环");
return;
}
for(int u : zeroDegree) {
dfs(u);
}
if(cyclic) {
return;
}
Collections.reverse(topo);
for (int n : topo) {
System.out.print(n);
}
}
}
拓扑排序java简单实现
最新推荐文章于 2023-11-05 23:11:45 发布