DFS算法实现拓扑排序
时间: 2023-08-20 21:11:54 浏览: 132
拓扑排序的实现
DFS算法实现拓扑排序的代码如下所示:
```java
package com.sh.zfc.graph.bfs;
import org.junit.Test;
import java.util.Arrays;
import java.util.Stack;
import static org.junit.Assert.*;
public class TopSortTest {
@Test
public void dfs() {
Digraph.GraphVertex\[\] vertices = new Digraph.GraphVertex\[4\];
vertices\[0\] = new Digraph.GraphVertex("A" , Arrays.asList(1,3));
vertices\[1\] = new Digraph.GraphVertex("B" , Arrays.asList(2,3));
vertices\[2\] = new Digraph.GraphVertex("C" );
vertices\[3\] = new Digraph.GraphVertex("D" );
Digraph<String> di = new Digraph<>(vertices);
TopSort topsort = new TopSort(di);
topsort.topSortByDFS(di);
Stack<Integer> result = topsort.getReversePost();
Stack<Integer> expect = new Stack<>();
expect.push(2);
expect.push(3);
expect.push(1);
expect.push(0);
assertEquals(expect,result);
}
}
```
这段代码使用了DFS算法来实现拓扑排序。首先创建了一个有向图,然后通过DFS算法进行拓扑排序。最后,将排序结果与预期结果进行比较,以验证算法的正确性。
#### 引用[.reference_title]
- *1* [浅谈拓扑排序(基于dfs算法)](https://blog.csdn.net/langzitan123/article/details/79687736)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [算法之拓朴排序DFS实现](https://blog.csdn.net/tony820418/article/details/84588614)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [拓扑排序(topological sort)DFS](https://blog.csdn.net/Tczxw/article/details/47334785)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文