java实现拓扑排序的例子
时间: 2023-07-09 15:47:25 浏览: 113
拓扑排序例子.docx
以下是Java实现拓扑排序的例子:
```java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class TopologicalSort {
public int[] topoSort(int numCourses, int[][] prerequisites) {
// 记录每个节点的入度
int[] inDegree = new int[numCourses];
// 记录每个节点的后继节点
ArrayList<Integer>[] nextNodes = new ArrayList[numCourses];
for (int i = 0; i < numCourses; i++) {
nextNodes[i] = new ArrayList<>();
}
// 构建图
for (int[] edge : prerequisites) {
int from = edge[1];
int to = edge[0];
inDegree[to]++;
nextNodes[from].add(to);
}
// 将入度为0的节点加入队列
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) {
queue.offer(i);
}
}
// 进行拓扑排序
int[] result = new int[numCourses];
int index = 0;
while (!queue.isEmpty()) {
int curr = queue.poll();
result[index++] = curr;
for (int next : nextNodes[curr]) {
inDegree[next]--;
if (inDegree[next] == 0) {
queue.offer(next);
}
}
}
// 判断是否存在环
if (index != numCourses) {
return new int[0];
}
return result;
}
}
```
使用方法:
```java
int numCourses = 4;
int[][] prerequisites = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};
TopologicalSort ts = new TopologicalSort();
int[] result = ts.topoSort(numCourses, prerequisites);
for (int i : result) {
System.out.print(i + " ");
}
```
输出结果为:0 1 2 3,表示拓扑排序的结果。
阅读全文