Search code examples
c#quickgraph

QuickGraph finding indegree of Vertices


I am using QuickGraph to create a directed acyclic graph. I need to find all vertices whose indegree is zero. I don't see this support on a graph's Vertices collection, or a way to filter using LINQ.

Here is a sample data structure I'm composing:

var componentGraph = new AdjacencyGraph<Component, Edge<Component>>();

var serverOnMachineA = new TalismaServerComponent("CLTDEPAPI10");
var serverOnMachineB = new TalismaServerComponent("CLTDEPAPI11");
var appServerOnMachineB = new TalismaAppServerComponent("CLTDEPAPI11");
var webComponentsOnMachineC = new TalismaWebComponentsComponent("CLTDEPFE1");

componentGraph.AddVertex(serverOnMachineA);
componentGraph.AddVertex(serverOnMachineB);
componentGraph.AddVertex(appServerOnMachineB);
componentGraph.AddVertex(webComponentsOnMachineC);

componentGraph.AddEdge(new Edge<Component>(appServerOnMachineB, serverOnMachineA));
componentGraph.AddEdge(new Edge<Component>(webComponentsOnMachineC, appServerOnMachineB));
componentGraph.AddEdge(new Edge<Component>(webComponentsOnMachineC, serverOnMachineB));

I simply need a list of the vertices in this graph that have no "in" edges (indegree=0).


Solution

  • You might need a different graph type. Diving a bit into the forums and source of QuickGraph I found the BidirectionalGraph class which is

    A mutable directed graph data structure efficient for sparse graph representation where out-edge and in-edges need to be enumerated. Requires twice as much memory as the adjacency graph.

    The method to retrieve the in-degree seems to be found on the IBidirectionalIncidenceGraph as this discussion implies.

    The data structure you use does not do book keeping on incoming edges, thus you would have to retrieve the in-degree of a vertex by iterating through all edges and looking at their target, which could be an expensive operation for big graphs.

    The BidirectionalGraph is quicker for that but takes twice as much memory space for the book-keeping. Using it you could do something like:

    var orphans = graph.Vertices.Where(v => graph.InDegree(v) == 0)