26 lines
736 B
C#
26 lines
736 B
C#
namespace NodePipeline.Engine.Graph;
|
|
|
|
public static class TopologicalSorter
|
|
{
|
|
public static List<string> Sort(Dictionary<string, List<string>> graph)
|
|
{
|
|
var indegree = graph.ToDictionary(kv => kv.Key, _ => 0);
|
|
foreach (var edges in graph.Values)
|
|
foreach (var to in edges)
|
|
indegree[to]++;
|
|
|
|
var queue = new Queue<string>(indegree.Where(kv => kv.Value == 0).Select(kv => kv.Key));
|
|
var result = new List<string>();
|
|
|
|
while (queue.Count > 0)
|
|
{
|
|
var n = queue.Dequeue();
|
|
result.Add(n);
|
|
foreach (var m in graph[n])
|
|
if (--indegree[m] == 0)
|
|
queue.Enqueue(m);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
} |