拓撲排序java簡單實現
阿新 • • 發佈:2018-12-14
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);
}
}
}