代码拉取完成,页面将自动刷新
/***
* 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;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。