图 - 拓扑排序

#!/usr/bin/env python3.3
# -*- coding:utf-8 -*-
# Copyright 2013

def topological_sort(graph, graph_size):
    topo_list = []
    indegree = {v: 0 for v in range(graph_size)}
    # 初始化每个顶点的入度
    for u in range(graph_size):
        for v in range(graph_size):
            if graph[u][v] is not None:
                indegree[v] += 1
    while indegree:
        visit_s = []
        # 查找入度为0的顶点
        for u, in_degree in indegree.items():
            if in_degree == 0:
                visit_s.append(u)
        # 移除入度为0的顶点,更新相邻顶点入度
        for u in visit_s:
            topo_list.append(u)
            for v in range(graph_size):
                if graph[u][v] is not None:
                    indegree[v] -= 1
            indegree.pop(u)
        if len(visit_s) == 0 and len(indegree) > 0:
            return None
    return topo_list

 

posted @ 2013-04-30 00:28  Leung文  阅读(153)  评论(0编辑  收藏  举报