深度优先拓扑排序算法
时间: 2023-12-17 17:29:00 浏览: 94
<<引用[1]:深度优先拓扑排序算法是一种用于有向无环图(DAG)的顶点的线性排序。在拓扑排序中,如果存在一条从顶点u到顶点v的路径,那么在拓扑排序中,u一定在v的前面。引用:深度优先搜索(DFS)是一种用于遍历或搜索树或图的算法。在DFS中,从根节点开始,沿着树的深度遍历树的节点,直到找到叶子节点或者目标节点。>>
以下是深度优先拓扑排序算法的演示:
```python
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSortUtil(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if not visited[i]:
self.topologicalSortUtil(i, visited, stack)
stack.insert(0, v)
def topologicalSort(self):
visited = [False] * self.V
stack = []
for i in range(self.V):
if not visited[i]:
self.topologicalSortUtil(i, visited, stack)
return stack
g = Graph(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)
print("拓扑排序结果:", g.topologicalSort()) # 输出:[5, 4, 2, 3, 1, 0]
```
阅读全文