Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication9
- {
- public class TopSort
- {
- List<int>[] Edges;
- int N;
- int[] Color;
- public int[] Numbers;
- Stack<int> Stack = new Stack<int>();
- public TopSort(List<int>[] graph)
- {
- Edges = graph;
- N = Edges.Length;
- Color = new int[N];
- for (int i = 0; i < N-1; i++)
- Color[i] = 0;
- Numbers = new int[N];
- }
- public bool topological_sort()
- {
- bool Cycle;
- for (int i= 0 ; i < N; i++)
- {
- Cycle = dfs(i);
- if (Cycle) throw new Exception("В графе есть цикл");
- }
- for (int i = 0; i < N; i++)
- {
- Numbers[Stack.Pop()] = i;
- }
- return true;
- }
- public bool dfs(int v)
- {
- if (Color[v] == 1) return true;
- if (Color[v] == 2) return false;
- Color[v] = 1;
- for (int i = 0; i < Edges[v].Count; i++)
- {
- if (dfs(Edges[v][i])) return true;
- }
- Stack.Push(v);
- Color[v] = 2;
- return false;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- List<int>[] mas = new List<int>[4]
- {
- new List<int>() { 3 },
- new List<int>() { },
- new List<int>() { 1 },
- new List<int>() { 1,2},
- };
- int[] num = new int[4];
- try
- {
- TopSort ts = new TopSort(mas);
- bool b = ts.topological_sort();
- foreach (int i in ts.Numbers)
- Console.WriteLine(i);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement