Example #1
0
        public static IEnumerable <Vertex <TVertexId> > InputsTopologicalSort <TVertexId, TVertexProperty, TEdgeProperty>(
            this IDirectedGraph <TVertexId, TVertexProperty, TEdgeProperty> graph,
            IComparer <TVertexId> vertexIdComparer)
        {
            if (graph.EdgesCount == 0)
            {
                return(graph.Vertices);
            }

            var order        = new List <Vertex <TVertexId> >();
            var inputDegrees = new Dictionary <Vertex <TVertexId>, int>();
            Heap <Vertex <TVertexId> > vertexHeap = new Heap <Vertex <TVertexId> >(
                ((vertex1, vertex2) => vertexIdComparer.Compare(vertex1.Id, vertex2.Id)));

            foreach (Vertex <TVertexId> vertex in graph.Vertices)
            {
                int degree = graph.GetInputDegree(vertex);

                inputDegrees.Add(vertex, degree);

                if (degree == 0)
                {
                    vertexHeap.Push(vertex);
                }
            }

            while (vertexHeap.Count > 0)
            {
                Vertex <TVertexId> vertex = vertexHeap.Pop();

                order.Add(vertex);
                inputDegrees.Remove(vertex);

                foreach (Vertex <TVertexId> neighbour in graph.GetNeighbours(vertex))
                {
                    --inputDegrees[neighbour];

                    if (inputDegrees[neighbour] == 0)
                    {
                        vertexHeap.Push(neighbour);
                    }
                }
            }

            return(order.Count == graph.VerticesCount
                ? order
                : throw new DirectedCyclicGraphException("Given graph contains a cycle"));
        }