图的dfs_拓扑排序
public class 图的dfs_拓扑排序 {
static final int n = 4;
static String[] v = {"a", "b", "c", "d"};
static int[][] graph = {
{0, 1, 0, 0},
{0, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
};
static int[] vis = new int[n];
static int[] topo = new int[n];
static int t = n;
public static void main(String[] args) {
for (int i = 0; i < n; i++) {
if (vis[i] == 1) continue;
boolean bool = dfs(i);
if (!bool) {
System.out.println(false);
return;
}
}
for (int i = 0; i < n; i++) {
System.out.println(v[topo[i]]);
}
}
private static boolean dfs(int i) {
vis[i] = -1;
for (int j = 0; j < n; j++) {
if (graph[i][j] > 0) {
if (vis[j] < 0) return false;
if (vis[j] == 0 && dfs(j) == false) return false;
}
}
topo[--t] = i;
vis[i] = 1;
return true;
}
}