Ai
1 Star 1 Fork 0

AndyZhang/C-Sharp-Algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
TopologicalSorter.cs 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
Ivandro Ismael 提交于 2018-05-21 07:50 +08:00 . remove redundant "else" / "else if"
/***
* Computes one topological sorting of a DAG (Directed Acyclic Graph).
* This class depends on the CyclesDetector static class.
*/
using System;
using System.Collections.Generic;
using DataStructures.Graphs;
namespace Algorithms.Graphs
{
public static class TopologicalSorter
{
/// <summary>
/// Private recursive helper.
/// </summary>
private static void _topoSortHelper<T>(IGraph<T> graph, T source, ref DataStructures.Lists.Stack<T> topoSortStack, ref HashSet<T> visited) where T : IComparable<T>
{
visited.Add(source);
foreach (var adjacent in graph.Neighbours(source))
if (!visited.Contains(adjacent))
_topoSortHelper<T>(graph, adjacent, ref topoSortStack, ref visited);
topoSortStack.Push(source);
}
/// <summary>
/// The Topological Sorting algorithm
/// </summary>
public static IEnumerable<T> Sort<T>(IGraph<T> Graph) where T : IComparable<T>
{
// If the graph is either null or is not a DAG, throw exception.
if (Graph == null)
throw new ArgumentNullException();
if (!Graph.IsDirected || CyclesDetector.IsCyclic<T>(Graph))
throw new Exception("The graph is not a DAG.");
var visited = new HashSet<T>();
var topoSortStack = new DataStructures.Lists.Stack<T>();
foreach (var vertex in Graph.Vertices)
if (!visited.Contains(vertex))
_topoSortHelper<T>(Graph, vertex, ref topoSortStack, ref visited);
return topoSortStack;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/strongandyzhang/C-Sharp-Algorithms.git
git@gitee.com:strongandyzhang/C-Sharp-Algorithms.git
strongandyzhang
C-Sharp-Algorithms
C-Sharp-Algorithms
master

搜索帮助