-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSorting.cs
48 lines (44 loc) · 1.01 KB
/
TopologicalSorting.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DA.Graphs;
namespace DA.Algorithms.Sorting
{
static class TopologicalSorting
{
public static void TopologicalSort (Graph graph)
{
int count = graph.Count;
int[] visited = new int[count];
Stack<int> stack = new Stack<int> ();
for (int i = 0; i < count; i++)
{
visited[i] = 0;
}
for (int i = 0; i < count; i++)
{
if(visited[i] == 0)
{
visited[i] = 1;
TopologicalSortDFS (graph, i, visited, stack);
}
}
}
private static void TopologicalSortDFS (Graph graph, int index, int[] visited, Stack<int> stack)
{
Graph.Node head = graph.GetNode (index);
while (head != null)
{
if (visited[head.destination] == 0)
{
visited[head.destination] = 1;
TopologicalSortDFS (graph, head.destination, visited, stack);
}
head = head.next;
}
stack.Push (index);
}
}
}