/// <summary> /// Creates graph consisting of strongly connected components only and then returns the /// minimum vertex among all the strongly connected components graph, ignores single vertex graph since it can't have a cycle /// potentially can return null. /// </summary> /// <param name="sccs"></param> /// <param name="graph"></param> /// <returns></returns> private Nullable <int> LeastIndexSCC(List <HashSet <int> > sccs, IDigraph graph) { int min = int.MaxValue; Nullable <int> minvertex = null; HashSet <int> minscc = null; foreach (HashSet <int> component in sccs) { if (component.Count == 1) { continue; } foreach (int vertex in component) { if (vertex < min) { min = vertex; minvertex = vertex; minscc = component; } } } if (minvertex == null) { return(null); } IDigraph graphscc = new Digraph(graph.VertexCount); for (int i = 0; i < graph.VertexCount; i++) { graphscc.AddVertex(); } for (int i = 0; i < graph.VertexCount; i++) { if (minscc.Contains(i)) { if (graph.GetDegreeOut(i) > 0) { foreach (int neighbor in graph.GetVertexNeighborsOut(i)) { if (minscc.Contains(neighbor)) { graphscc.AddEdge(i, neighbor); } } } } } Nullable <int> potentialminvertex = null; if (graphscc.GetDegreeOut(min) > 0 || graphscc.GetDegreeIn(min) > 0) { potentialminvertex = minvertex; } return(potentialminvertex); }
/// <summary> /// (DIRECTED GRAPH) -Create a subgraph of an input graph between a start and end vertex (includes start and end vertex) /// </summary> /// <param name="startindex"></param> /// <param name="endvertex"></param> /// <param name="graph"></param> /// <returns></returns> public IDigraph CreateSubGraph(int startindex, int endvertex, IDigraph graph) { IDigraph subgraph = new Digraph(graph.VertexCount); for (int i = 0; i < graph.VertexCount; i++) { subgraph.AddVertex(); } for (int i = startindex; i <= endvertex; i++) { List <int> neighbors = (List <int>)graph.GetVertexNeighborsOut(i); foreach (int neighbor in neighbors) { if (neighbor >= startindex && neighbor <= endvertex) { subgraph.AddEdge(i, neighbor); } } } return(subgraph); }
/// <summary> /// (DIRECTED GRAPH) -Create a copy of the directed graph that is reversed /// </summary> /// <param name="graph"></param> /// <returns></returns> public IDigraph ReverseGraph(IDigraph graph) { IDigraph reversegraph = new Digraph(graph.VertexCount); for (int i = 0; i < graph.VertexCount; i++) { reversegraph.AddVertex(); } for (int i = 0; i < graph.VertexCount; i++) { List <int> vertexneighbors = (List <int>)graph.GetVertexNeighborsOut(i); //for each vertex that is connected, create a reverse edge with its neighbors if (vertexneighbors.Count > 0) { foreach (int neighbor in vertexneighbors) { reversegraph.AddEdge(neighbor, i); } } } return(reversegraph); }