java拓扑排序代码
时间: 2023-10-22 22:29:12 浏览: 99
拓扑排序代码
以下是一个Java拓扑排序的代码示例:
```
public class TopologicalSort {
public static void topSort(List<Node> vs) {
Queue<Node> q = new LinkedList<Node>();
int size = vs.size();
int count = 0;
// 初始化队列
for (Node n : vs) {
if (n.indegree == 0)
q.add(n);
}
// 将入度为0的节点输出,并且将其所指向的节点的入度值-1
while (!q.isEmpty()) {
Node v = q.poll();
count++;
for (Node w : v.getChild()) {
if (--w.indegree == 0)
q.add(w);
}
}
// 计算节点的个数和最后出队列的个数,若不一样则有环
if (count != size) {
System.out.println("图有圈");
}
}
}
```
上述代码中,`topSort`方法接受一个节点列表作为参数,其中每个节点都包含一个`indegree`属性和一个`getChild()`方法来获取指向的节点。该方法使用队列来执行拓扑排序算法,首先将入度为0的节点加入队列,然后依次出队节点,将其所指向的节点的入度值减1,再将入度为0的节点加入队列。最后,通过计算节点的个数和最后出队列的个数来判断是否存在环。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [拓扑排序(java实现)](https://blog.csdn.net/qq_40877841/article/details/83419272)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [十种JAVA排序算法实例](https://download.csdn.net/download/weixin_38647567/12813080)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [【Java】拓扑排序](https://blog.csdn.net/rellvera/article/details/126087737)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文