public double Compute(Vertex src, Vertex sink) { m_ResidualEdgeCapacities = new EdgeDoubleDictionary(); // initializing foreach(Vertex u in VisitedGraph.Vertices) foreach(Edge e in u.OutEdges) ResidualCapacities[e] = Capacities[e]; Colors[sink] = GraphColor.Gray; while (Colors[sink] != GraphColor.White) { VertexBuffer Q = new VertexBuffer(); ResidualEdgePredicate ep = new ResidualEdgePredicate(ResidualCapacities); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(resg,Q,Colors); PredecessorVisitor pred = new PredecessorVisitor(Predecessors); pred.RegisterHandlers(bfs); bfs.Compute(src); if (Colors[sink] != GraphColor.White) Augment(src, sink, pred.Predecessors); } // while double flow = 0; foreach(Edge e in src.OutEdges) flow += (EdgeCapacities[e] - ResidualEdgeCapacities[e]); return flow; }
public void GraphWithSelfEdges( [UsingLinear(2, 9)] int i, [UsingLinear(0, 10)] int j ) { if (i == 0 && j == 0) { return; } Random rnd = new Random(); g = new AdjacencyGraph <int, Edge <int> >(true); RandomGraphFactory.Create <int, Edge <int> >(g, new IntVertexFactory(), FactoryCompiler.GetEdgeFactory <int, Edge <int> >(), rnd, i, j, true); algo = new BreadthFirstSearchAlgorithm <int, Edge <int> >(g); try { algo.InitializeVertex += new VertexEventHandler <int>(this.InitializeVertex); algo.DiscoverVertex += new VertexEventHandler <int>(this.DiscoverVertex); algo.ExamineEdge += new EdgeEventHandler <int, Edge <int> >(this.ExamineEdge); algo.ExamineVertex += new VertexEventHandler <int>(this.ExamineVertex); algo.TreeEdge += new EdgeEventHandler <int, Edge <int> >(this.TreeEdge); algo.NonTreeEdge += new EdgeEventHandler <int, Edge <int> >(this.NonTreeEdge); algo.GrayTarget += new EdgeEventHandler <int, Edge <int> >(this.GrayTarget); algo.BlackTarget += new EdgeEventHandler <int, Edge <int> >(this.BlackTarget); algo.FinishVertex += new VertexEventHandler <int>(this.FinishVertex); parents.Clear(); distances.Clear(); currentDistance = 0; sourceVertex = RandomGraphFactory.GetVertex(g, rnd); foreach (int v in g.Vertices) { distances[v] = int.MaxValue; parents[v] = v; } distances[sourceVertex] = 0; algo.Compute(sourceVertex); CheckBfs(); } finally { algo.InitializeVertex -= new VertexEventHandler <int>(this.InitializeVertex); algo.DiscoverVertex -= new VertexEventHandler <int>(this.DiscoverVertex); algo.ExamineEdge -= new EdgeEventHandler <int, Edge <int> >(this.ExamineEdge); algo.ExamineVertex -= new VertexEventHandler <int>(this.ExamineVertex); algo.TreeEdge -= new EdgeEventHandler <int, Edge <int> >(this.TreeEdge); algo.NonTreeEdge -= new EdgeEventHandler <int, Edge <int> >(this.NonTreeEdge); algo.GrayTarget -= new EdgeEventHandler <int, Edge <int> >(this.GrayTarget); algo.BlackTarget -= new EdgeEventHandler <int, Edge <int> >(this.BlackTarget); algo.FinishVertex -= new VertexEventHandler <int>(this.FinishVertex); } }
public void Init() { this.parents = new Dictionary <int, int>(); this.distances = new Dictionary <int, int>(); this.currentDistance = 0; this.currentVertex = 0; this.algo = null; this.g = null; }
public override double Compute(IVertex src, IVertex sink) { if (src == null) { throw new ArgumentNullException("src"); } if (sink == null) { throw new ArgumentNullException("sink"); } IVertexEnumerator enumerator = base.VisitedGraph.get_Vertices().GetEnumerator(); while (enumerator.MoveNext()) { IVertex vertex = enumerator.get_Current(); IEdgeEnumerator enumerator2 = base.VisitedGraph.OutEdges(vertex).GetEnumerator(); while (enumerator2.MoveNext()) { IEdge edge = enumerator2.get_Current(); base.ResidualCapacities.set_Item(edge, base.Capacities.get_Item(edge)); } } base.Colors.set_Item(sink, 2); while (base.Colors.get_Item(sink) != null) { PredecessorRecorderVisitor vis = new PredecessorRecorderVisitor(base.Predecessors); VertexBuffer q = new VertexBuffer(); BreadthFirstSearchAlgorithm algorithm = new BreadthFirstSearchAlgorithm(this.ResidualGraph, q, base.Colors); algorithm.RegisterPredecessorRecorderHandlers(vis); algorithm.Compute(src); if (base.Colors.get_Item(sink) != null) { this.Augment(src, sink); } } double num = 0.0; IEdgeEnumerator enumerator3 = base.VisitedGraph.OutEdges(src).GetEnumerator(); while (enumerator3.MoveNext()) { IEdge edge2 = enumerator3.get_Current(); num += base.Capacities.get_Item(edge2) - base.ResidualCapacities.get_Item(edge2); } return num; }
internal void ComputeNoInit(IVertex s) { m_VertexQueue = new PriorithizedVertexBuffer(m_Distances); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm( VisitedGraph, m_VertexQueue, Colors ); bfs.InitializeVertex += this.InitializeVertex; bfs.DiscoverVertex += this.DiscoverVertex; bfs.ExamineEdge += this.ExamineEdge; bfs.ExamineVertex += this.ExamineVertex; bfs.FinishVertex += this.FinishVertex; bfs.TreeEdge += new EdgeHandler(this.TreeEdge); bfs.GrayTarget += new EdgeHandler(this.GrayTarget); bfs.Visit(s); }
/// <summary> /// Computes a set of eulerian trail, starting at <paramref name="s"/> /// that spans the entire graph. /// </summary> /// <remarks> /// <para> /// This method computes a set of eulerian trail starting at <paramref name="s"/> /// that spans the entire graph.The algorithm outline is as follows: /// </para> /// <para> /// The algorithms iterates throught the Eulerian circuit of the augmented /// graph (the augmented graph is the graph with additional edges to make /// the number of odd vertices even). /// </para> /// <para> /// If the current edge is not temporary, it is added to the current trail. /// </para> /// <para> /// If the current edge is temporary, the current trail is finished and /// added to the trail collection. The shortest path between the /// start vertex <paramref name="s"/> and the target vertex of the /// temporary edge is then used to start the new trail. This shortest /// path is computed using the <see cref="BreadthFirstSearchAlgorithm"/>. /// </para> /// </remarks> /// <param name="s">start vertex</param> /// <returns>eulerian trail set, all starting at s</returns> /// <exception cref="ArgumentNullException">s is a null reference.</exception> /// <exception cref="Exception">Eulerian trail not computed yet.</exception> public EdgeCollectionCollection Trails(IVertex s) { if (s==null) throw new ArgumentNullException("s"); if (this.Circuit.Count==0) throw new Exception("Circuit is empty"); // find the first edge in the circuit. int i=0; for(i=0;i<this.Circuit.Count;++i) { IEdge e = this.Circuit[i]; if (TemporaryEdges.Contains(e)) continue; if (e.Source == s) break; } if (i==this.Circuit.Count) throw new Exception("Did not find vertex in eulerian trail?"); // create collections EdgeCollectionCollection trails = new EdgeCollectionCollection(); EdgeCollection trail = new EdgeCollection(); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(VisitedGraph); PredecessorRecorderVisitor vis = new PredecessorRecorderVisitor(); bfs.RegisterPredecessorRecorderHandlers(vis); bfs.Compute(s); // go throught the edges and build the predecessor table. int start = i; for (;i<this.Circuit.Count;++i) { IEdge e = this.Circuit[i]; if (TemporaryEdges.Contains(e)) { // store previous trail and start new one. if(trail.Count != 0) trails.Add(trail); // start new trail // take the shortest path from the start vertex to // the target vertex trail = vis.Path(e.Target); } else trail.Add(e); } // starting again on the circuit for (i=0;i<start;++i) { IEdge e = this.Circuit[i]; if (TemporaryEdges.Contains(e)) { // store previous trail and start new one. if(trail.Count != 0) trails.Add(trail); // start new trail // take the shortest path from the start vertex to // the target vertex trail = vis.Path(e.Target); } else trail.Add(e); } // adding the last element if (trail.Count!=0) trails.Add(trail); return trails; }
public void BreadthFirstSearch(IVertexAndEdgeListGraph<string, Edge<string>> g) { var bfs = new BreadthFirstSearchAlgorithm<string, Edge<string>>(g); bfs.Compute(); }
private void RemoveIrrelevantBranches(AdjacencyGraph<IBuilder, EquatableEdge<IBuilder>> graph, IBuilder rootBuilder) { var bfs = new BreadthFirstSearchAlgorithm<IBuilder, EquatableEdge<IBuilder>>(graph); var toKeep = new HashSet<EquatableEdge<IBuilder>>(); var buildersToKeep = new HashSet<IBuilder>(); bfs.TreeEdge += e => toKeep.Add(e); bfs.NonTreeEdge += e => toKeep.Add(e); bfs.DiscoverVertex += b => buildersToKeep.Add(b); bfs.Compute(rootBuilder); graph.RemoveEdgeIf(edge => !toKeep.Contains(edge)); graph.RemoveVertexIf(vertex => !buildersToKeep.Contains(vertex)); }
/// <summary> /// Computes the maximum flow between <paramref name="src"/> and /// <paramref name="sink"/> /// </summary> /// <param name="src"></param> /// <param name="sink"></param> /// <returns></returns> public override double Compute(IVertex src, IVertex sink) { if (src==null) throw new ArgumentNullException("src"); if (sink==null) throw new ArgumentNullException("sink"); foreach(IVertex u in VisitedGraph.Vertices) { foreach(IEdge e in VisitedGraph.OutEdges(u)) { ResidualCapacities[e] = Capacities[e]; } } Colors[sink] = GraphColor.Gray; while (Colors[sink] != GraphColor.White) { PredecessorRecorderVisitor vis = new PredecessorRecorderVisitor( Predecessors ); VertexBuffer Q = new VertexBuffer(); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm( ResidualGraph, Q, Colors ); bfs.RegisterPredecessorRecorderHandlers(vis); bfs.Compute(src); if (Colors[sink] != GraphColor.White) Augment(src, sink); } // while double flow=0; foreach(IEdge e in VisitedGraph.OutEdges(src)) flow += (Capacities[e] - ResidualCapacities[e]); return flow; }
private void GlobalDistanceUpdate() { IVertexEnumerator enumerator = this.VisitedGraph.get_Vertices().GetEnumerator(); while (enumerator.MoveNext()) { IVertex vertex = enumerator.get_Current(); base.Colors.set_Item(vertex, 0); this.Distances.set_Item(vertex, this.n); } this.Distances.set_Item(this.sink, 0); for (int i = 0; i <= this.maxDistance; i++) { this.layers[i].ActiveVertices.Clear(); this.layers[i].InactiveVertices.Clear(); } this.maxDistance = this.maxActive = 0; this.minActive = this.n; BreadthFirstSearchAlgorithm algorithm = new BreadthFirstSearchAlgorithm(this.ResidualGraph, new VertexBuffer(), base.Colors); DistanceRecorderVisitor visitor = new DistanceRecorderVisitor(this.Distances); algorithm.TreeEdge += new EdgeEventHandler(visitor, (IntPtr) this.TreeEdge); algorithm.DiscoverVertex += new VertexEventHandler(this, (IntPtr) this.GlobalDistanceUpdateHelper); algorithm.Compute(this.sink); }
private void RemoveIrrelevantBranches(AdjacencyGraph<IBuilder, EquatableEdge<IBuilder>> graph, IBuilder rootBuilder) { var bfs = new BreadthFirstSearchAlgorithm<IBuilder, EquatableEdge<IBuilder>>(graph); bfs.Compute(rootBuilder); var toKeep = new HashSet<IBuilder>(bfs.VisitedGraph.Vertices); graph.RemoveVertexIf(v => !toKeep.Contains(v)); }
protected void CheckBfs(IVertexListGraph g, BreadthFirstSearchAlgorithm bfs) { // All white vertices should be unreachable from the source. foreach(IVertex v in g.Vertices) { if (bfs.Colors[v]==GraphColor.White) { //!IsReachable(start,u,g); } } // The shortest path to a child should be one longer than // shortest path to the parent. foreach(IVertex v in g.Vertices) { if (Parents[v] != v) // *ui not the root of the bfs tree Assert.AreEqual(Distances[v], Distances[Parents[v]] + 1); } }
public void GraphWithSelfEdges() { Random rnd = new Random(); for (int i = 0; i <10; ++i) for (int j = 0; j < i*i; ++j) { AdjacencyGraph g = new AdjacencyGraph( new QuickGraph.Providers.VertexProvider(), new QuickGraph.Providers.EdgeProvider(), true); RandomGraph.Graph(g,i,j,rnd,true); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(g); bfs.InitializeVertex += new VertexEventHandler( this.InitializeVertex); bfs.DiscoverVertex += new VertexEventHandler(this.DiscoverVertex); bfs.ExamineEdge += new EdgeEventHandler(this.ExamineEdge); bfs.ExamineVertex += new VertexEventHandler(this.ExamineVertex); bfs.TreeEdge += new EdgeEventHandler(this.TreeEdge); bfs.NonTreeEdge += new EdgeEventHandler(this.NonTreeEdge); bfs.GrayTarget += new EdgeEventHandler(this.GrayTarget); bfs.BlackTarget += new EdgeEventHandler(this.BlackTarget); bfs.FinishVertex += new VertexEventHandler(this.FinishVertex); Parents.Clear(); Distances.Clear(); m_CurrentDistance = 0; m_SourceVertex = RandomGraph.Vertex(g, rnd); foreach(IVertex v in g.Vertices) { Distances[v]=int.MaxValue; Parents[v]=v; } Distances[SourceVertex]=0; bfs.Compute(SourceVertex); CheckBfs(g,bfs); } }
//======================================================================= // This is a breadth-first search over the residual graph // (well, actually the reverse of the residual graph). // Would be cool to have a graph view adaptor for hiding certain // edges, like the saturated (non-residual) edges in this case. // Goldberg's implementation abused "distance" for the coloring. private void GlobalDistanceUpdate() { foreach (IVertex u in VisitedGraph.Vertices) { Colors[u] = GraphColor.White; Distances[u] = n; } Distances[sink] = 0; for (int l = 0; l <= maxDistance; ++l) { layers[l].ActiveVertices.Clear(); layers[l].InactiveVertices.Clear(); } maxDistance = maxActive = 0; minActive = n; BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm( ResidualGraph, new VertexBuffer(), Colors ); DistanceRecorderVisitor vis = new DistanceRecorderVisitor(Distances); bfs.TreeEdge += new EdgeEventHandler(vis.TreeEdge); bfs.DiscoverVertex += new VertexEventHandler(GlobalDistanceUpdateHelper); bfs.Compute(sink); }
static void Main(string[] args) { try { /* VertexStringDictionary verticesNames = new VertexStringDictionary(); EdgeStringDictionary edgesNames = new EdgeStringDictionary(); EdgeDoubleDictionary edgesWeights = new EdgeDoubleDictionary(); IncidenceGraph g = new IncidenceGraph(true); // adding vertex Vertex u = g.AddVertex(); verticesNames[u]="u"; Vertex v = g.AddVertex(); verticesNames[v]="v"; Vertex w = g.AddVertex(); verticesNames[w]="w"; Vertex x = g.AddVertex(); verticesNames[x]="x"; Vertex y = g.AddVertex(); verticesNames[y]="y"; Vertex z = g.AddVertex(); verticesNames[z]="z"; // adding edges Edge uv = g.AddEdge(u,v); edgesNames[uv]="uv"; edgesWeights[uv]=1; Edge ux = g.AddEdge(u,x); edgesNames[ux]="ux"; edgesWeights[ux]=0.8; Edge wu = g.AddEdge(w,u); g.AddEdge(w,u); edgesNames[wu]="wu"; edgesWeights[wu]=0.2; Edge xv = g.AddEdge(x,v); edgesNames[xv]="xv"; edgesWeights[xv]=1.1; Edge vy = g.AddEdge(v,y); edgesNames[vy]="vy"; edgesWeights[vy]=2.0; Edge wy = g.AddEdge(w,y); edgesNames[wy]="wy"; edgesWeights[wy]=1.5; Edge yw = g.AddEdge(y,w); edgesNames[yw]="yw"; edgesWeights[yw]=0.2; Edge wz = g.AddEdge(w,z); edgesNames[wz]="wz"; edgesWeights[wz]=0.1; RandomGraph.Graph(g, 20,50,new Random(),true); /* // do a dfs serach Console.WriteLine("---- DepthFirstSearch"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); //TestDepthFirstSearchVisitor dfsVis = // new TestDepthFirstSearchVisitor(dfs,verticesNames); AlgorithmTracerVisitor dfstracer = new AlgorithmTracerVisitor(g,"dfs",".",GraphvizImageType.Png); dfstracer.VertexLabels = verticesNames; dfstracer.RegisterVertexHandlers(dfs); dfstracer.RegisterEdgeHandlers(dfs); dfs.Compute(); */ Vertex source = u; source = RandomGraph.Vertex(g,new Random()); Console.WriteLine("source: {0}",source.GetHashCode()); Console.WriteLine("---- BreathFirstSearch"); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(g); TestBreadthFirstSearchVisitor bfsVis = new TestBreadthFirstSearchVisitor(bfs,verticesNames,source); AlgorithmTracerVisitor bfstracer = new AlgorithmTracerVisitor(g,"bfs",".",GraphvizImageType.Png); // bfstracer.VertexLabels = verticesNames; bfs.RegisterTreeEdgeBuilderHandlers(bfsTracer); bfs.RegisterVertexColorizeHandlers(bfsTracer); bfs.Compute(source); /* Console.WriteLine("---- Dijkstra"); DijkstraShortestPathAlgorithm dij = new DijkstraShortestPathAlgorithm( g, edgesWeights ); TestDijkstraShortestPathVisitor dijVis = new TestDijkstraShortestPathVisitor(dij,verticesNames); AlgorithmTracerVisitor dijtracer = new AlgorithmTracerVisitor(g,"dij",".",GraphvizImageType.Png); dijtracer.VertexLabels = verticesNames; dijtracer.EdgeLabels = edgesWeights; dijtracer.RegisterVertexHandlers(dij); // dijtracer.RegisterEdgeHandlers(dij); dij.Compute(g.Vertex(0)); Console.WriteLine("Distance from {0}", verticesNames[g.Vertex(0)]); foreach(DictionaryEntry de in dij.Distances) { Console.WriteLine("\t-> {0}, {1}", verticesNames[(Vertex)de.Key], de.Value.ToString() ); } Console.WriteLine("---- Topological sort"); VertexCollection vs = new VertexCollection(); TopologicalSortAlgorithm tps= new TopologicalSortAlgorithm(g); tps.Compute(vs); foreach(Vertex ve in vs) { Console.WriteLine("v - {0}",verticesNames[ve]); } Console.WriteLine("--- graphviz output"); GraphvizWriterAlgorithm gw = new GraphvizWriterAlgorithm( g,"dotgenerator",".",GraphvizImageType.Png); TestGraphvizVertex gv = new TestGraphvizVertex(verticesNames); gw.WriteVertex += new VertexHandler( gv.WriteVertex ); gw.WriteEdge+= new EdgeHandler( gv.WriteEdge ); gw.Write(GraphvizImageType.Png); gw.Write(GraphvizImageType.Svg); gw.Write(GraphvizImageType.Svgz); gw.Write(GraphvizImageType.Gif); gw.Write(GraphvizImageType.Jpeg); */ Console.WriteLine("Test finished"); String s2=Console.ReadLine(); } catch(Exception ex) { Console.WriteLine(ex.ToString()); String s=Console.ReadLine(); } }
public EdgeCollectionCollection Trails(IVertex s) { if (s == null) { throw new ArgumentNullException("s"); } if (this.Circuit.Count == 0) { throw new Exception("Circuit is empty"); } int num = 0; num = 0; while (num < this.Circuit.Count) { IEdge edge = this.Circuit.get_Item(num); if (!this.TemporaryEdges.Contains(edge) && (edge.get_Source() == s)) { break; } num++; } if (num == this.Circuit.Count) { throw new Exception("Did not find vertex in eulerian trail?"); } EdgeCollectionCollection collections = new EdgeCollectionCollection(); EdgeCollection edges = new EdgeCollection(); BreadthFirstSearchAlgorithm algorithm = new BreadthFirstSearchAlgorithm(this.VisitedGraph); PredecessorRecorderVisitor vis = new PredecessorRecorderVisitor(); algorithm.RegisterPredecessorRecorderHandlers(vis); algorithm.Compute(s); int num2 = num; while (num < this.Circuit.Count) { IEdge edge2 = this.Circuit.get_Item(num); if (this.TemporaryEdges.Contains(edge2)) { if (edges.Count != 0) { collections.Add(edges); } edges = vis.Path(edge2.get_Target()); } else { edges.Add(edge2); } num++; } for (num = 0; num < num2; num++) { IEdge edge3 = this.Circuit.get_Item(num); if (this.TemporaryEdges.Contains(edge3)) { if (edges.Count != 0) { collections.Add(edges); } edges = vis.Path(edge3.get_Target()); } else { edges.Add(edge3); } } if (edges.Count != 0) { collections.Add(edges); } return collections; }
public void RunBfs <TVertex, TEdge>(IVertexAndEdgeListGraph <TVertex, TEdge> g, TVertex sourceVertex) where TEdge : IEdge <TVertex> { var parents = new Dictionary <TVertex, TVertex>(); var distances = new Dictionary <TVertex, int>(); TVertex currentVertex = default(TVertex); int currentDistance = 0; var algo = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(g); algo.InitializeVertex += u => { Assert.AreEqual(algo.VertexColors[u], GraphColor.White); }; algo.DiscoverVertex += u => { Assert.AreEqual(algo.VertexColors[u], GraphColor.Gray); if (u.Equals(sourceVertex)) { currentVertex = sourceVertex; } else { Assert.IsNotNull(currentVertex); Assert.AreEqual(parents[u], currentVertex); Assert.AreEqual(distances[u], currentDistance + 1); Assert.AreEqual(distances[u], distances[parents[u]] + 1); } }; algo.ExamineEdge += args => { Assert.AreEqual(args.Source, currentVertex); }; algo.ExamineVertex += args => { var u = args; currentVertex = u; // Ensure that the distances monotonically increase. Assert.IsTrue( distances[u] == currentDistance || distances[u] == currentDistance + 1 ); if (distances[u] == currentDistance + 1) // new level { ++currentDistance; } }; algo.TreeEdge += args => { var u = args.Source; var v = args.Target; Assert.AreEqual(algo.VertexColors[v], GraphColor.White); Assert.AreEqual(distances[u], currentDistance); parents[v] = u; distances[v] = distances[u] + 1; }; algo.NonTreeEdge += args => { var u = args.Source; var v = args.Target; Assert.IsFalse(algo.VertexColors[v] == GraphColor.White); if (algo.VisitedGraph.IsDirected) { // cross or back edge Assert.IsTrue(distances[v] <= distances[u] + 1); } else { // cross edge (or going backwards on a tree edge) Assert.IsTrue( distances[v] == distances[u] || distances[v] == distances[u] + 1 || distances[v] == distances[u] - 1 ); } }; algo.GrayTarget += args => { Assert.AreEqual(algo.VertexColors[args.Target], GraphColor.Gray); }; algo.BlackTarget += args => { Assert.AreEqual(algo.VertexColors[args.Target], GraphColor.Black); foreach (var e in algo.VisitedGraph.OutEdges(args.Target)) { Assert.IsFalse(algo.VertexColors[e.Target] == GraphColor.White); } }; algo.FinishVertex += args => { Assert.AreEqual(algo.VertexColors[args], GraphColor.Black); }; parents.Clear(); distances.Clear(); currentDistance = 0; foreach (var v in g.Vertices) { distances[v] = int.MaxValue; parents[v] = v; } distances[sourceVertex] = 0; algo.Compute(sourceVertex); // All white vertices should be unreachable from the source. foreach (var v in g.Vertices) { if (algo.VertexColors[v] == GraphColor.White) { //!IsReachable(start,u,g); } } // The shortest path to a child should be one longer than // shortest path to the parent. foreach (var v in g.Vertices) { if (!parents[v].Equals(v)) // *ui not the root of the bfs tree { Assert.AreEqual(distances[v], distances[parents[v]] + 1); } } }
private bool IsOptimal(MaximumFlowAlgorithm maxFlow) { // check if mincut is saturated... FilteredVertexListGraph residualGraph = new FilteredVertexListGraph( maxFlow.VisitedGraph, new ReversedResidualEdgePredicate(maxFlow.ResidualCapacities, maxFlow.ReversedEdges) ); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(residualGraph); VertexIntDictionary distances = new VertexIntDictionary(); DistanceRecorderVisitor vis = new DistanceRecorderVisitor(distances); bfs.RegisterDistanceRecorderHandlers(vis); bfs.Compute(sink); return distances[source] >= maxFlow.VisitedGraph.VerticesCount; }
public void GraphWithSelfEdgesPUT1(int v, int e, bool self) { AdjacencyGraph g = null; RandomGraph.Graph(g, v, e, new Random(), self); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(g); }
public void ComputeNoInit(IVertex s) { this.vertexQueue = new PriorithizedVertexBuffer(this.distances); BreadthFirstSearchAlgorithm algorithm = new BreadthFirstSearchAlgorithm(this.VisitedGraph, this.vertexQueue, this.Colors); algorithm.InitializeVertex += this.InitializeVertex; algorithm.DiscoverVertex += this.DiscoverVertex; algorithm.ExamineEdge += this.ExamineEdge; algorithm.ExamineVertex += this.ExamineVertex; algorithm.FinishVertex += this.FinishVertex; algorithm.TreeEdge += new EdgeEventHandler(this, (IntPtr) this.TreeEdge); algorithm.GrayTarget += new EdgeEventHandler(this, (IntPtr) this.GrayTarget); algorithm.Visit(s); }
public void GraphWithSelfEdgesPUT2() { AdjacencyGraph g = null; BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(g); }
private void breadthFirstSearchItem_Click(object sender, System.EventArgs e) { if (this.netronPanel.Graph==null) throw new Exception("Generate a graph first"); if (this.netronPanel.Populator==null) throw new Exception("Populator should not be null."); ResetVertexAndEdgeColors(); // create algorithm this.edgeColors=new EdgeColorDictionary(); foreach(IEdge edge in this.netronPanel.Graph.Edges) this.edgeColors[edge]=GraphColor.White; this.vertexColors = new VertexColorDictionary(); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm( this.netronPanel.Graph, new VertexBuffer(), this.vertexColors); // create tracer LayoutAlgorithmTraverVisitor tracer = new LayoutAlgorithmTraverVisitor(this.netronPanel.Populator); // link to algo bfs.RegisterTreeEdgeBuilderHandlers(tracer); bfs.RegisterVertexColorizerHandlers(tracer); bfs.TreeEdge +=new EdgeEventHandler(dfs_TreeEdge); bfs.NonTreeEdge+=new EdgeEventHandler(dfs_BackEdge); bfs.BlackTarget +=new EdgeEventHandler(dfs_ForwardOrCrossEdge); // add handler to tracers tracer.UpdateVertex +=new ShapeVertexEventHandler(tracer_UpdateVertex); tracer.UpdateEdge +=new ConnectionEdgeEventHandler(tracer_UpdateEdge); // running algorithm VertexMethodCaller vm= new VertexMethodCaller( new ComputeVertexDelegate(bfs.Compute), Traversal.FirstVertex(this.netronPanel.Graph) ); Thread thread = new Thread(new ThreadStart(vm.Run)); thread.Start(); }
public void GraphWithSelfEdgesPUT(AdjacencyGraph g, int loopBound) { Random rnd = new Random(); Init(); for (int i = 0; i < loopBound; ++i) { for (int j = 0; j < i * i; ++j) { RandomGraph.Graph(g, i, j, rnd, true); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(g); bfs.InitializeVertex += new VertexHandler(this.InitializeVertex); bfs.DiscoverVertex += new VertexHandler(this.DiscoverVertex); bfs.ExamineEdge += new EdgeHandler(this.ExamineEdge); bfs.ExamineVertex += new VertexHandler(this.ExamineVertex); bfs.TreeEdge += new EdgeHandler(this.TreeEdge); bfs.NonTreeEdge += new EdgeHandler(this.NonTreeEdge); bfs.GrayTarget += new EdgeHandler(this.GrayTarget); bfs.BlackTarget += new EdgeHandler(this.BlackTarget); bfs.FinishVertex += new VertexHandler(this.FinishVertex); Parents.Clear(); Distances.Clear(); m_CurrentDistance = 0; m_SourceVertex = RandomGraph.Vertex(g, rnd); var choose = PexChoose.FromCall(this); if(choose.ChooseValue<bool>("to add a self ede")) { IVertex selfEdge = RandomGraph.Vertex(g, rnd); g.AddEdge(selfEdge, selfEdge); } // g.RemoveEdge(RandomGraph.Edge(g, rnd)); foreach (IVertex v in g.Vertices) { Distances[v] = int.MaxValue; Parents[v] = v; } Distances[SourceVertex] = 0; bfs.Compute(SourceVertex); CheckBfs(g, bfs); } } }