TopologicalSort

We found 10 examples in language CSharp for this search. You will see 42 fragments of code.
        [TestMethod]
        public void TopoTest_Empty()
        {
            TopologicalSort.Sort(new List<TopologicalSort.Node>());
        }
        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TopoTest_Null()
        {
            TopologicalSort.Sort(null);        
        }
        [TestMethod]
        public void TopoTest_One()
        {
            TopologicalSort.Node node = new TopologicalSort.Node();
            List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {node};

            List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);
            Assert.AreEqual(sortedNodes[0], nodes[0]);
        }

        [TestMethod]
        public void TopoTest_NoDependencies()
        {
            TopologicalSort.Node a = new TopologicalSort.Node();
            TopologicalSort.Node b = new TopologicalSort.Node();
            List<TopologicalSort.Node> nodes = new List<TopologicalSort.Node> {a, b};
            List<TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);
            Assert.IsTrue(sortedNodes.Contains(a));
            Assert.IsTrue(sortedNodes.Contains(b));
        }

        [Fact]
        public void Test_Topological_Sorting()
        {
            var edgeList = new int[3][];
            edgeList[0] = new int[] { 1, 2 };
            edgeList[1] = new int[] { 2, 3 };
            edgeList[2] = new int[] { 3, 4 };
            var graph = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(4, graph);
            Assert.Equal(new int[] { 4, 3, 2, 1 }, topologicalSort.Sort());
        }

        [Fact]
        public void Test_is_graph_topological_sortable_for_cycle_case()
        {
            var edgeList = new int[3][];
            edgeList[0] = new[] { 1, 2 };
            edgeList[1] = new[] { 2, 3 };
            edgeList[2] = new[] { 3, 1 };
            var graph = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(3, graph);
            Assert.False(topologicalSort.IsSortable());
        }

        [Fact]
        public void Test_is_graph_topological_sortable_for_non_cycle_case()
        {
            var edgeList = new int[3][];
            edgeList[0] = new[] { 1, 2 };
            edgeList[1] = new[] { 2, 3 };
            edgeList[2] = new[] { 3, 4 };
            var graph = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(3, graph);
            Assert.True(topologicalSort.IsSortable());
        }


			[DebuggerHidden]
			IEnumerator<Node> IEnumerable<Node>.GetEnumerator()
			{
				if (Interlocked.CompareExchange(ref this.$PC, 0, -2) == -2)
				{
					return this;
				}
				return new TopologicalSort.<>c__Iterator0();
			}

		private static void Visit(Node n)
		{
			if (!TopologicalSort.s_NodeStates.ContainsKey(n))
			{
				TopologicalSort.s_NodeStates[n] = TopologicalSort.NodeState.Visited;
				foreach (Edge current in n.outputEdges)
				{
					TopologicalSort.Visit(current.toSlot.node);
				}
				TopologicalSort.s_SortedNodes.Add(n);
			}
		}

		public static void Sort(Graph g)
		{
			TopologicalSort.s_Graph = g;
			TopologicalSort.s_SortedNodes = new List<Node>();
			TopologicalSort.s_NodeStates = new Dictionary<Node, TopologicalSort.NodeState>();
			foreach (Node current in g.nodes)
			{
				TopologicalSort.Visit(current);
			}
		}

        static void Main(string[] args)
        {
            var output = TopologicalSort(new List<int> { 1, 2, 3, 4 }, new List<int[]> {
                new int[]{ 1, 2 },
                new int[]{ 1, 3 },
                new int[]{ 3, 2 },
                new int[]{ 4, 2 },
                new int[]{ 4, 3 }
            });

            Console.ReadLine();

        }

        public static List<int> getOrderedGraphs(JobGraph jobGraph)
        {
            List<int> topologicalSort = new List<int>();
            foreach (JobNode node in jobGraph.nodes)
            {
                bool containsCycle = getTopologicalSort(node, topologicalSort);
                if(containsCycle)
                {
                    return new List<int>();
                }
            }

            return topologicalSort;
        }

        private void InitGraphSearch()
        {
            parents = new int[v];
            discovered = new bool[v];
            processed = new bool[v];
            entryTime = new int[v];
            exitTime = new int[v];

            isBipartite = true;
            finishedDFS = false;
            
            for (int i = 0; i < v; i++)
            {
                parents[i] = -1;
            }
        }

        public void AddEdge(int x, int y)
        {
            adjList[x].AddLast(y);
            if(!directed)
                adjList[y].AddLast(x);
        }

        public void PrintGraph()
        {
            for(int i=0;i<adjList.Length;i++)
            {
                foreach(int val in adjList[i])
                {
                    Console.Write(val + "->");
                }
                Console.WriteLine();
            }
        }

        public void BFS(int start)
        {
            Queue<int> q = new Queue<int>();

            discovered[start] = true;
            q.Enqueue(start);

            while(q.Count != 0)
            {
                int currVertex = q.Dequeue();

                ProcessEarly(currVertex);
                foreach(int currEdge in adjList[currVertex])
                {
                    if(!processed[currEdge] || directed)
                    {
                        ProcessEdge(currVertex, currEdge);
                    }
                    if (!discovered[currEdge])
                    {
                        q.Enqueue(currEdge);
                        discovered[currEdge] = true;
                        parents[currEdge] = currVertex;
                    }
                }
                processed[currVertex] = true;
                ProcessLate(currVertex);
            }
            Console.WriteLine("total edges " + e);
        }

        public void ShortestPath(int u, int v)
        {
            InitGraphSearch();
            BFS(u);
            FindPath(u, v);
        }

        private void FindPath(int start, int end)
        {
            if(start == end || end == -1)
            {
                Console.Write(start);
            }else
            {
                FindPath(start, parents[end]);
                Console.Write(end);
            }
        }


        internal void Append(ISet<OrderedProcess> collection)
        {
            _collections.Add(collection);
        }

        #region IEnumerable
        /// <summary>
        /// Gets the enumerator which enumerates sets of processes, where a set can be executed in any order
        /// </summary>
        /// <returns></returns>
        IEnumerator<ISet<OrderedProcess>> IEnumerable<ISet<OrderedProcess>>.GetEnumerator()
        {
            return _collections.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through the processes
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        public System.Collections.IEnumerator GetEnumerator()
        {
            return (this as IEnumerable<OrderedProcess>).GetEnumerator();
        }

        /// <summary>
        /// Gets the enumerator which enumerates through the processes in an order to be executed
        /// </summary>
        /// <returns></returns>
        IEnumerator<OrderedProcess> IEnumerable<OrderedProcess>.GetEnumerator()
        {
            IEnumerable<IEnumerable<OrderedProcess>> collections = this;

            return collections.SelectMany(collection => collection).GetEnumerator();
        }

        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn(
            int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, // rect of corner
            int nWidthEllipse, int nHeightEllipse // dimension of ellipse
        );

        private void Dashboard_Load(object sender, EventArgs e)
        {
            TBMinimum.Text = "8";
            TBMaximum.Text = "12";

            TBMinimum.Enabled = false;
            TBMaximum.Enabled = false;

            BGenerate.Enabled = false;
            BView.Visible = false;

            if (active)
            {
                Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 35, 35));
                PBViewGraph.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, PBViewGraph.Width, PBViewGraph.Height, 25, 25));
                LBTopologicalSorting.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, LBTopologicalSorting.Width, LBTopologicalSorting.Height, 25, 25));
                BView.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, BView.Width, BView.Height, 25, 25));
                BGenerate.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, BGenerate.Width, BGenerate.Height, 20, 20));
                TBMinimum.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, TBMinimum.Width, TBMinimum.Height, 15, 15));
                TBBelongs.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, TBBelongs.Width, TBBelongs.Height, 15, 15));
                TBMaximum.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, TBMaximum.Width, TBMaximum.Height, 15, 15));
                LBVertex.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, LBVertex.Width, LBVertex.Height, 20, 20));
                LBEdge.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, LBEdge.Width, LBEdge.Height, 20, 20));
            }
        }

        private void Generate_Click(object sender, EventArgs e)
        {
            for (int z = 0; z < 12; z++) rGraphs.Add(new GraphRelation(vertex[z], edge[z]));
            graph.exportResources(list, rGraphs);

            value = Convert.ToInt32(TBBelongs.Text);
            if (value >= Convert.ToInt32(TBMinimum.Text) && value <= Convert.ToInt32(TBMaximum.Text)) graph.viewGraph(value, tSort);
            else if (value < Convert.ToInt32(TBMinimum.Text)) MessageBox.Show("Sorry, but the entered value is less than the Minimum", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else if (value > Convert.ToInt32(TBMaximum.Text)) MessageBox.Show("Sorry, but the value entered is greater than the Maximum", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            if (view) this.topologicalSort.Close();
            BView.Visible = true;
        }

        private void Belongs_Valid(object sender, EventArgs e)
        {
            BGenerate.Enabled = TBBelongs.TextLength > 0;
        }

        private void Belongs_Text(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar)) e.Handled = false;
            else if (Char.IsControl(e.KeyChar)) e.Handled = false;
            else e.Handled = true;
        }

        private void TopologicalSort_Click(object sender, EventArgs e)
        {
            topologicalSort = new TopologicalSortForm();

            for (int z = 0; z < 12; z++)
            {
                topologicalSort.list[z] = list[z];
                topologicalSort.vertex[z] = vertex[z];
                topologicalSort.edge[z] = edge[z];
            }

            topologicalSort.value = Convert.ToInt32(TBBelongs.Text);
            for (int t = 0; t < Convert.ToInt32(TBBelongs.Text); t++) topologicalSort.tSort.Add(tSort[t]);
            topologicalSort.Show();
            view = true;
        }


        IEnumerator<ISet<OrderedProcess>> IEnumerable<ISet<OrderedProcess>>.GetEnumerator()
        {
            return _collections.GetEnumerator();
        }

        public IEnumerator GetEnumerator()
        {
            return (this as IEnumerable<OrderedProcess>).GetEnumerator();
        }

        IEnumerator<OrderedProcess> IEnumerable<OrderedProcess>.GetEnumerator()
        {
            IEnumerable<IEnumerable<OrderedProcess>> collections = this;

            return collections.SelectMany(collection => collection).GetEnumerator();
        }

        internal void Append(ISet<OrderedProcess> collection)
        {
            _collections.Add(collection);
        }

        IEnumerator<ISet<OrderedProcess<T>>> IEnumerable<ISet<OrderedProcess<T>>>.GetEnumerator()
        {
            return _collections.GetEnumerator();
        }


        public IEnumerator GetEnumerator()
        {
            return (this as IEnumerable<OrderedProcess<T>>).GetEnumerator();
        }


        public static void FakeInput()
        {
            Console.SetIn(new StringReader(input));
        }

        static void Main()
        {
            FakeInput();

            var dict = new Dictionary<int, string>();

            var graph = GetGraphWithAdjacencyList(dict);
            var sorted = TopologicalSort(graph);

            var result = new string[sorted.Length];

            for (int i = 0; i < sorted.Length; i++)
            {
                result[i] = dict[sorted[i]];
            }

            Console.WriteLine(string.Join(" ", result));
        }

        public static int[] TopologicalSort(List<List<Node>> graph)
        {
            var used = new HashSet<int>();
            var stack = new Stack<int>();

            for (int i = 1; i < graph.Count; i++)
            {
                if (used.Contains(i))
                {
                    continue;
                }
                used.Add(i);

                TopologicalSort(graph, used, stack, i);
            }

            var result = new int[graph.Count - 1];

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = stack.Pop();
            }

            return result;
        }

        private static void TopologicalSort(List<List<Node>> graph, HashSet<int> used, Stack<int> stack, int currentNode)
        {
            foreach (var next in graph[currentNode])
            {
                if (used.Contains(next.Vertex))
                {
                    continue;
                }
                used.Add(next.Vertex);
                TopologicalSort(graph, used, stack, next.Vertex);
            }
            stack.Push(currentNode);
        }

        public static List<List<Node>> GetGraphWithAdjacencyList()
        {
            var verticesCount = int.Parse(Console.ReadLine());

            var edgesCount = int.Parse(Console.ReadLine());

            var graph = new List<List<Node>>(verticesCount + 1);

            for (int i = 0; i < verticesCount + 1; i++)
            {
                graph.Add(new List<Node>());
            }

            for (int i = 0; i < edgesCount; i++)
            {
                var vertices = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

                var from = vertices[0];
                var to = vertices[1];

                var node = new Node();
                node.Vertex = vertices[1];
                graph[from].Add(node);
            }

            return graph;
        }

        public static List<List<Node>> GetGraphWithAdjacencyList(Dictionary<int, string> dict)
        {
            var verticesCount = int.Parse(Console.ReadLine());

            var edgesCount = int.Parse(Console.ReadLine());

            var graph = new List<List<Node>>(verticesCount + 1);

            for (int i = 0; i < verticesCount + 1; i++)
            {
                graph.Add(new List<Node>());
            }

            var dictCount = 1;

            for (int i = 0; i < edgesCount; i++)
            {
                var vertices = Console.ReadLine().Split(' ').ToArray();
                
                if (!dict.ContainsValue(vertices[0]))
                {
                    dict.Add(dictCount, vertices[0]);
                    ++dictCount;
                }
                if (!dict.ContainsValue(vertices[1]))
                {
                    dict.Add(dictCount, vertices[1]);
                    ++dictCount;
                }

                var from = dict.First(x => x.Value == vertices[0]).Key;
                var to = dict.First(x => x.Value == vertices[1]).Key;

                var node = new Node();
                node.Vertex = to;
                graph[from].Add(node);
            }

            return graph;
        }

        public static int[] TopologicalSort(List<List<Node>> graph)
        {
            var used = new HashSet<int>();
            var stack = new Stack<int>();

            for (int i = 1; i < graph.Count; i++)
            {
                if (used.Contains(i))
                {
                    continue;
                }
                used.Add(i);

                TopologicalSort(graph, used, stack, i);
            }

            var result = new int[graph.Count - 1];

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = stack.Pop();
            }

            return result;
        }

        private static void TopologicalSort(List<List<Node>> graph, HashSet<int> used, Stack<int> stack, int currentNode)
        {
            foreach (var next in graph[currentNode])
            {
                if (used.Contains(next.Vertex))
                {
                    continue;
                }
                used.Add(next.Vertex);
                TopologicalSort(graph, used, stack, next.Vertex);
            }
            stack.Push(currentNode);
        }

VirtoCommerce.Platform.Core.Common.TopologicalSort : Object

Methods :

public static List<T> Sort(HashSet<T> nodes = , HashSet<Tuple<TT>> edges = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()