拓扑排序代码java
时间: 2023-12-22 21:29:33 浏览: 84
以下是一个使用Java实现拓扑排序的示例代码:
```java
import java.util.*;
public class TopologicalSort {
private int V; // 顶点的数量
private List<List<Integer>> adj; // 邻接表
public TopologicalSort(int v) {
V = v;
adj = new ArrayList<>(v);
for (int i = 0; i < v; ++i)
adj.add(new ArrayList<>());
}
public void addEdge(int v, int w) {
adj.get(v).add(w);
}
public void topologicalSort() {
int[] inDegree = new int[V]; // 记录每个顶点的入度
// 计算每个顶点的入度
for (int v = 0; v < V; ++v) {
List<Integer> neighbors = adj.get(v);
for (int neighbor : neighbors) {
inDegree[neighbor]++;
}
}
Queue<Integer> queue = new LinkedList<>();
for (int v = 0; v < V; ++v) {
if (inDegree[v] == 0) {
queue.add(v);
}
}
List<Integer> result = new ArrayList<>();
while (!queue.isEmpty()) {
int v = queue.poll();
result.add(v);
List<Integer> neighbors = adj.get(v);
for (int neighbor : neighbors) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) {
queue.add(neighbor);
}
}
}
// 输出拓扑排序结果
for (int v : result) {
System.out.print(v + " ");
}
}
public static void main(String[] args) {
TopologicalSort g = new TopologicalSort(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
System.out.println("拓扑排序结果:");
g.topologicalSort();
}
}
```
阅读全文