python 实现algorithm topo卡恩拓扑算法

algorithm topo卡恩拓扑算法介绍

卡恩拓扑算法(也称为Kahn算法或Kahn's Topological Sort Algorithm)是一种用于对有向无环图(DAG)进行拓扑排序的经典算法。拓扑排序是将有向无环图的节点按照依赖关系进行排序的过程,使得所有的依赖关系都得到满足。即,如果图中存在一条边u->v,则节点u在排序结果中一定出现在节点v之前。

卡恩拓扑算法的基本思想如下:

初始化:计算图中每个节点的入度(即有多少条边指向该节点)。同时,创建一个队列,并将所有入度为0的节点加入队列中。

处理队列中的节点:当队列非空时,从队列中取出一个节点,将其加入到拓扑排序的结果中。然后,遍历该节点的所有邻居节点,对每个邻居节点,将其入度减1。如果减1后某个邻居节点的入度变为0,则将其加入队列中。

重复上述步骤:重复步骤2,直到队列为空。

检查结果:如果最终拓扑排序的结果中包含了图中所有的节点,则说明图中没有环,拓扑排序成功;如果结果中节点数量少于图中的节点总数,则说明图中存在环,无法进行拓扑排序。

下面是使用Python实现卡恩拓扑算法的一个简单示例:

python 复制代码
def kahnTopologicalSort(graph):
    from collections import deque
    
    # 计算每个节点的入度
    in_degree = {node: 0 for node in graph}
    for node in graph:
        for neighbor in graph[node]:
            in_degree[neighbor] += 1
    
    # 将所有入度为0的节点加入队列
    queue = deque([node for node in graph if in_degree[node] == 0])
    topo_sort = []
    
    # 当队列非空时继续处理
    while queue:
        node = queue.popleft()
        topo_sort.append(node)
        
        # 遍历当前节点的所有邻居节点
        for neighbor in graph[node]:
            in_degree[neighbor] -= 1
            if in_degree[neighbor] == 0:
                queue.append(neighbor)
    
    # 检查是否所有节点都被排序
    if len(topo_sort) == len(graph):
        return topo_sort
    else:
        return None  # 图中存在环,无法进行拓扑排序

# 示例图,使用字典表示,键为节点,值为该节点的邻居节点列表
graph = {
    'A': ['B', 'C'],
    'B': ['D'],
    'C': ['D'],
    'D': []
}

# 调用函数进行拓扑排序
print(kahnTopologicalSort(graph))

请注意,上述代码中的图是用字典表示的,其中键是节点,值是该节点的邻居节点列表。你可以根据实际需求调整图的表示方式。

卡恩拓扑算法在任务调度、依赖关系管理、编译优化中的数据流分析等场景中有广泛的应用。

algorithm topo卡恩拓扑算法python实现样例

以下是Python实现卡恩拓扑算法的示例代码:

python 复制代码
def topological_sort(graph):
    # 计算每个节点的入度
    in_degrees = {node: 0 for node in graph}
    for node in graph:
        for neighbor in graph[node]:
            in_degrees[neighbor] += 1

    # 将入度为0的节点加入队列
    queue = [node for node in graph if in_degrees[node] == 0]

    # 依次取出队列中的节点,并更新其邻居节点的入度
    result = []
    while queue:
        node = queue.pop(0)
        result.append(node)
        for neighbor in graph[node]:
            in_degrees[neighbor] -= 1
            if in_degrees[neighbor] == 0:
                queue.append(neighbor)

    # 检查是否存在环
    if len(result) != len(graph):
        raise ValueError("存在环路")

    return result

示例用法:

python 复制代码
graph = {
    'A': ['B', 'C'],
    'B': ['C', 'D'],
    'C': ['D'],
    'D': []
}

result = topological_sort(graph)
print(result)

输出:

复制代码
['A', 'B', 'C', 'D']

这表示按照拓扑排序的顺序,首先访问节点A,然后是节点B,接着是节点C,最后是节点D。

相关推荐
卷无止境5 小时前
Python数据进阶专题:用声明式验证让数据管道告别"惊喜"
后端·python·数据分析
浩瀚地学5 小时前
【面试算法笔记】0105-数组-螺旋矩阵
java·开发语言·笔记·算法·面试
码云骑士6 小时前
61-LangChain-vs-LlamaIndex-选型对比-功能矩阵-混用实践
python·线性代数·矩阵·langchain
阿豪只会阿巴6 小时前
两小时快速入门 FastAPI--第一回
开发语言·python·fastapi
Hesionberger6 小时前
动态规划与二分法破解最长递增子序列
java·数据结构·python·算法·leetcode
JustNow_Man6 小时前
【Claude Code】 中给 Python + XML 项目建立可靠验证体系
xml·linux·python
薛定猫AI6 小时前
【技术干货】多模型AI编程代理实战:用Python统一接入Claude Opus 4.8
人工智能·python·ai编程
imuliuliang6 小时前
关于Kruskal 算法在图优化问题中的扩展应用7
算法
老约家的可汗6 小时前
Linux中基础IO
linux·服务器·算法
二宝哥7 小时前
08.Python流程控制详解:从基础到实践
开发语言·python