Python implementation of topological algorithms

foreword

Topological sorting is an important sorting algorithm in graph theory for sorting directed acyclic graphs (DAGs). In topological sorting, the vertices of the graph represent tasks, and the directed edges represent dependencies between tasks. Topological sorting algorithms find an order that satisfies all task dependencies.

Algorithm principle

The basic principles of the topological sorting algorithm are as follows:

  1. Create an empty sorted result list.
  2. Find all vertices with in-degree 0 in the graph (that is, vertices without dependencies), and add them to the sorted result list.
  3. Remove the vertex and its associated edges.
  4. Repeat steps 2 and 3 until all vertices in the graph are processed.
  5. If the length of the sorted result list is equal to the number of vertices in the graph, the topological sort is successful; otherwise, there are cycles in the graph and the topological sort cannot be performed.

Python implementation

The following is a sample code to implement the topological sorting algorithm in Python:

from collections import deque

def topological_sort(graph):
    # 统计每个顶点的入度
    in_degree = {
    
    v: 0 for v in graph}
    
    # 计算每个顶点的入度
    for v in graph:
        for neighbor in graph[v]:
            in_degree[neighbor] += 1
    
    # 将入度为0的顶点加入队列
    queue = deque([v for v in graph if in_degree[v] == 0])
    
    # 保存拓扑排序的结果
    result = []
    
    while queue:
        # 取出队列中的顶点
        v = queue.popleft()
        result.append(v)
        
        # 移除顶点及其相关边
        for neighbor in graph[v]:
            in_degree[neighbor] -= 1
            if in_degree[neighbor] == 0:
                queue.append(neighbor)
    
    # 判断是否存在环
    if len(result) != len(graph):
        raise ValueError("图中存在环,无法进行拓扑排序。")
    
    return result

# 测试
graph = {
    
    
    'A': ['B', 'C'],
    'B': ['D'],
    'C': ['D', 'E'],
    'D': ['F'],
    'E': ['F'],
    'F': []
}

try:
    result = topological_sort(graph)
    print("拓扑排序结果:", result)
except ValueError as e:
    print(e)

In the above code, graphit represents the adjacency list representation of the graph, in which each vertex is represented as a key, and its corresponding value is a list, and the vertices that are directly connected to the vertex are stored in the list.

After running the code, the result of topological sorting will be output.

That's it for a sample code implementing a topological sort algorithm using Python. With this algorithm, we can perform a directed acyclic graph

Sort, find the order that satisfies the task dependencies.

Guess you like

Origin blog.csdn.net/chy555chy/article/details/130938158