Code Practice Journal | Day58_Graph08 Topological Sorting

1. 概念

在一个有向无环图(DAG)中,根据节点的依赖关系,对所有的节点进行线性排序的算法

拓扑排序的结果不一定是唯一的

2. 实现

2.1 BFS(卡恩算法)

1、步骤

2、代码实现

以KamaCoder 117.软体构建
题目:117. 软件构建 (kamacoder.com)

class Program
{
    public static void Main(string[] args)
    {
        // 处理输入
        string[] dimensions = Console.ReadLine().Split();
        int n = int.Parse(dimensions[0]);
        int m = int.Parse(dimensions[1]);
        // 邻接表 && 入度
        List<int>[] graph = new List<int>[n];
        for (int i = 0; i < n; i++)
        {
            graph[i] = new List<int>();
        }
        int[] indegree = new int[n];
        for (int i = 0; i < m; i++)
        {
            string[] nodes = Console.ReadLine().Split();
            int parent = int.Parse(nodes[0]);
            int child = int.Parse(nodes[1]);
            graph[parent].Add(child);
            indegree[child]++;
        }


        // TS & 输出
        List<int> result = new List<int>();
        TStra(graph, indegree, result, n);
        Console.WriteLine(result.Count == n ? string.Join(" ", result) : "-1");
    }

    public static void TStra(List<int>[] graph, int[] indegree, List<int> result, int n)
    {
        Queue<int> nodes = new Queue<int>();
        for (int i = 0; i < indegree.Length; i++)
        {
            if (indegree[i] == 0)
            {
                nodes.Enqueue(i);
                indegree[i] = -1;
            }
        }
        if (nodes.Count == 0) return;

        while (nodes.Count > 0)
        {
            int cur = nodes.Dequeue();
            result.Add(cur);

            foreach (int child in graph[cur])
            {
                indegree[child]--;
            }
        }

        if (result.Count == n) return;
        else
        {
            TStra(graph, indegree, result, n);
        }
    }
}
2.2 DFS(待更)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值