Exemplo n.º 1
0
        public long Solve(long nodeCount, long[][] edges)
        {
            Stack <long> stack = new Stack <long>();

            bool[] visited = new bool[nodeCount];
            Node[] nodes   = Q3Acyclic.GetDirectedGraph(nodeCount, edges);

            for (long i = 0; i < nodeCount; i++)
            {
                if (!visited[i])
                {
                    FillOrder(i, nodes, visited, stack);
                }
            }
            Node[] reversedGraph = GetReversedGraph(nodeCount, edges);

            visited = new bool[nodeCount];
            long curr  = 0;
            long count = 0;

            while (stack.Count != 0)
            {
                curr = stack.Pop();
                if (!visited[curr])
                {
                    DFS(reversedGraph, curr, visited);
                    count++;
                }
            }

            return(count);
        }
Exemplo n.º 2
0
        public long[] Solve(long nodeCount, long[][] edges)
        {
            Node[] nodes = Q3Acyclic.GetDirectedGraph(nodeCount, edges);

            Queue <long> queue = new Queue <long>();

            for (long i = 0; i < nodeCount; i++)
            {
                if (nodes[i].InDegree == 0)
                {
                    queue.Enqueue(i);
                }
            }
            long[] topologicalSort = new long[nodeCount];
            long   index           = 0;
            long   current         = 0;

            while (queue.Count != 0)
            {
                current = queue.Dequeue();
                topologicalSort[index] = current + 1;
                index++;
                if (nodes[current] != null)
                {
                    foreach (long child in nodes[current].Children)
                    {
                        if (nodes[child] != null)
                        {
                            nodes[child].InDegree--;
                            if (nodes[child].InDegree == 0)
                            {
                                queue.Enqueue(child);
                            }
                        }
                    }
                }
            }
            return(topologicalSort);
        }