//=======================================================================
        // 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);
        }
Beispiel #2
0
    void SearchGraph(
        BidirectionalGraph <Vertex, SEdge <Vertex> > graph,
        VertexPredecessorRecorderObserver <Vertex, SEdge <Vertex> >
        observer = null
        )
    {
        BreadthFirstSearchAlgorithm <Vertex, SEdge <Vertex> > bfs =
            new BreadthFirstSearchAlgorithm <Vertex, SEdge <Vertex> >
                (graph);

        if (observer == null)
        {
            bfs.Compute();
        }
        else
        {
            using (observer.Attach(bfs)) {
                bfs.Compute();

                foreach (
                    KeyValuePair <Vertex, SEdge <Vertex> > pair in
                    observer.VerticesPredecessors
                    )
                {
                    Debug.Log(
                        pair.Value.Source.Point +
                        " -> " +
                        pair.Value.Target.Point
                        );
                }
            }
        }
    }
Beispiel #3
0
        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 SetRootVertex_Throws()
        {
            var graph     = new AdjacencyGraph <TestVertex, Edge <TestVertex> >();
            var algorithm = new BreadthFirstSearchAlgorithm <TestVertex, Edge <TestVertex> >(graph);

            SetRootVertex_Throws_Test(algorithm);
        }
Beispiel #5
0
        private void GenerateSpanningTree()
        {
            _spanningTree = new BidirectionalGraph <TVertex, Edge <TVertex> >(false);
            _spanningTree.AddVertexRange(VisitedGraph.Vertices);
            IQueue <TVertex> vb = new QuikGraph.Collections.Queue <TVertex>();

            vb.Enqueue(VisitedGraph.Vertices.OrderBy(v => VisitedGraph.InDegree(v)).First());

            switch (Parameters.SpanningTreeGeneration)
            {
            case SpanningTreeGeneration.BFS:
                var bfs = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph, vb, new Dictionary <TVertex, GraphColor>());
                bfs.TreeEdge += e =>
                {
                    ThrowIfCancellationRequested();
                    _spanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target));
                };
                bfs.Compute();
                break;

            case SpanningTreeGeneration.DFS:
                var dfs = new DepthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
                dfs.TreeEdge += e =>
                {
                    ThrowIfCancellationRequested();
                    _spanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target));
                };
                dfs.Compute();
                break;
            }
        }
        public static TryFunc <TVertex, IEnumerable <TEdge> > TreeBreadthFirstSearch <TVertex, TEdge>(
#if !NET20
            this
#endif
            IVertexListGraph <TVertex, TEdge> visitedGraph,
            TVertex root)
            where TEdge : IEdge <TVertex>
        {
            Contract.Requires(visitedGraph != null);
            Contract.Requires(root != null);
            Contract.Requires(visitedGraph.ContainsVertex(root));
            Contract.Ensures(Contract.Result <TryFunc <TVertex, IEnumerable <TEdge> > >() != null);

            var algo = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(visitedGraph);
            var predecessorRecorder = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            using (predecessorRecorder.Attach(algo))
                algo.Compute(root);

            var predecessors = predecessorRecorder.VertexPredecessors;

            return(delegate(TVertex v, out IEnumerable <TEdge> edges)
            {
                return EdgeExtensions.TryGetPath(predecessors, v, out edges);
            });
        }
        public void ClearRootVertex()
        {
            var graph     = new AdjacencyGraph <int, Edge <int> >();
            var algorithm = new BreadthFirstSearchAlgorithm <int, Edge <int> >(graph);

            ClearRootVertex_Test(algorithm);
        }
        public void ExamineEdge(Object sender, EdgeEventArgs args)
        {
            Assert.IsTrue(sender is BreadthFirstSearchAlgorithm);
            BreadthFirstSearchAlgorithm algo = (BreadthFirstSearchAlgorithm)sender;

            Assert.AreSame(args.Edge.Source, CurrentVertex);
        }
Beispiel #9
0
        public NeuralNetwork
            (AdjacencyGraph <INeuron, Connection> network,
            ICollection <INeuron> inputNeurons,
            ICollection <INeuron> outputNeurons)
        {
            _network       = network;
            _outputNeurons = outputNeurons;
            _inputNeurons  = inputNeurons;

            AlphaVertex = new EmptyNeuron("Alpha");
            _network.AddVertex(AlphaVertex);
            foreach (var inputNeuron in _inputNeurons)
            {
                _network.AddEdge(new Connection(AlphaVertex, inputNeuron, 0d));
            }

            OmegaVertex = new EmptyNeuron("Omega");
            _network.AddVertex(OmegaVertex);
            foreach (var outputNeuron in _outputNeurons)
            {
                _network.AddEdge(new Connection(outputNeuron, OmegaVertex, 0d));
            }

            _algorithm              = new BreadthFirstSearchAlgorithm <INeuron, Connection>(_network);
            _algorithm.ExamineEdge += AddSignal;
            _algorithm.SetRootVertex(AlphaVertex);
        }
        protected virtual void GenerateSpanningTree(CancellationToken cancellationToken)
        {
            SpanningTree = new BidirectionalGraph <TVertex, Edge <TVertex> >(false);
            SpanningTree.AddVertexRange(VisitedGraph.Vertices.OrderBy(v => VisitedGraph.InDegree(v)));

            EdgeAction <TVertex, TEdge> action = e =>
            {
                cancellationToken.ThrowIfCancellationRequested();
                SpanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target));
            };

            switch (Parameters.SpanningTreeGeneration)
            {
            case SpanningTreeGeneration.BFS:
                var bfsAlgo = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
                bfsAlgo.TreeEdge += action;
                bfsAlgo.Compute();
                break;

            case SpanningTreeGeneration.DFS:
                var dfsAlgo = new DepthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
                dfsAlgo.TreeEdge           += action;
                dfsAlgo.ForwardOrCrossEdge += action;
                dfsAlgo.Compute();
                break;
            }
        }
        public void NonTreeEdge(Object sender, EdgeEventArgs args)
        {
            Assert.IsTrue(sender is BreadthFirstSearchAlgorithm);
            BreadthFirstSearchAlgorithm algo = (BreadthFirstSearchAlgorithm)sender;

            IVertex u = args.Edge.Source;
            IVertex v = args.Edge.Target;

            Assert.IsFalse(algo.Colors[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
                    );
            }
        }
        public void GrayTarget(Object sender, EdgeEventArgs args)
        {
            Assert.IsTrue(sender is BreadthFirstSearchAlgorithm);
            BreadthFirstSearchAlgorithm algo = (BreadthFirstSearchAlgorithm)sender;

            Assert.AreEqual(algo.Colors[args.Edge.Target], GraphColor.Gray);
        }
        public void FinishVertex(Object sender, VertexEventArgs args)
        {
            Assert.IsTrue(sender is BreadthFirstSearchAlgorithm);
            BreadthFirstSearchAlgorithm algo = (BreadthFirstSearchAlgorithm)sender;

            Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.Black);
        }
        protected override void InternalCompute()
        {
            this.bfs      = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(this.VisitedGraph);
            this.observer = new VertexPredecessorRecorderObserver <TVertex, TEdge>();

            try
            {
                this.observer.Attach(this.bfs);
                this.bfs.DiscoverVertex += new VertexEventHandler <TVertex>(bfs_DiscoverVertex);
                bfs.Compute();
                this.OnIterationEnded(EventArgs.Empty);
            }
            finally
            {
                if (this.observer != null)
                {
                    this.observer.Detach(this.bfs);
                    this.observer = null;
                }
                if (this.bfs != null)
                {
                    this.bfs.DiscoverVertex -= new VertexEventHandler <TVertex>(bfs_DiscoverVertex);
                    this.bfs = null;
                }
            }
        }
        public void Walk()
        {
            var breadthFirstSearchAlgorithm = new BreadthFirstSearchAlgorithm <string, ToscaGraphEdge>(graph);

            breadthFirstSearchAlgorithm.DiscoverVertex += nodeTypeName => { action(nodeTypeName, nodeTypes[nodeTypeName]); };
            breadthFirstSearchAlgorithm.Compute(ToscaDefaults.ToscaNodesRoot);
        }
Beispiel #16
0
        public static double MeasureBFSQuickGraphSpeed(string path)
        {
            AdjacencyGraph <int, Edge <int> > graph = Util.ReadMatrixMarketFileToQuickGraph(path);
            var algo = new BreadthFirstSearchAlgorithm <int, Edge <int> >(graph);

            return(MeasureQuickGraphAlgorithmSpeed(algo));
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            //Read file
            Console.WriteLine("Please provide a file name:");
            var fileName = Console.ReadLine();

            if (String.IsNullOrEmpty(fileName))
            {
                Console.WriteLine("Please provide a file name.");
                return;
            }

            if (!File.Exists(fileName))
            {
                Console.WriteLine($"File {fileName} is not found.");
                Console.ReadKey();
                return;
            }

            //Get log file name
            Console.WriteLine("Please provide a output file name:");
            var outputFileName = Console.ReadLine();

            if (String.IsNullOrEmpty(outputFileName))
            {
                Console.WriteLine("Please provide a file name.");
                return;
            }

            //Collect input data
            var text   = File.ReadAllText(fileName);
            var lines  = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            var height = lines.Count() - 1;
            var width  = lines[0].Split(' ').Count();

            var labyrinth = new int[height, width];

            for (int i = 0; i < height; i++)
            {
                var line = lines[i].Split(' ');
                for (int j = 0; j < line.Length; j++)
                {
                    labyrinth[i, j] = int.Parse(line[j]);
                }
            }

            var startCoordinates = lines.Last().Split(' ');
            var x = int.Parse(startCoordinates[0]);
            var y = int.Parse(startCoordinates[1]);

            //Execute algorithm
            //using (var algorithm = new DepthFirstSearchAlgorithm(labyrinth, y - 1, x - 1, new FileLoggerService(outputFileName)))
            using (var algorithm = new BreadthFirstSearchAlgorithm(labyrinth, y - 1, x - 1, new FileLoggerService(outputFileName)))
            {
                algorithm.Execute();
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
        /// <summary>
        /// Computes the maximum flow between Source and Sink.
        /// </summary>
        /// <returns></returns>
        protected override void InternalCompute()
        {
            if (this.Source == null)
            {
                throw new InvalidOperationException("Source is not specified");
            }
            if (this.Sink == null)
            {
                throw new InvalidOperationException("Sink is not specified");
            }


            if (this.Services.CancelManager.IsCancelling)
            {
                return;
            }

            var g = this.VisitedGraph;

            foreach (var u in g.Vertices)
            {
                foreach (var e in g.OutEdges(u))
                {
                    var capacity = this.Capacities(e);
                    if (capacity < 0)
                    {
                        throw new InvalidOperationException("negative edge capacity");
                    }
                    this.ResidualCapacities[e] = capacity;
                }
            }

            this.VertexColors[Sink] = GraphColor.Gray;
            while (this.VertexColors[Sink] != GraphColor.White)
            {
                var vis = new VertexPredecessorRecorderObserver <TVertex, TEdge>(
                    this.Predecessors
                    );
                var queue = new QuickGraph.Collections.Queue <TVertex>();
                var bfs   = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(
                    this.ResidualGraph,
                    queue,
                    this.VertexColors
                    );
                using (vis.Attach(bfs))
                    bfs.Compute(this.Source);

                if (this.VertexColors[this.Sink] != GraphColor.White)
                {
                    this.Augment(this.Source, this.Sink);
                }
            } // while

            this.MaxFlow = 0;
            foreach (var e in g.OutEdges(Source))
            {
                this.MaxFlow += (this.Capacities(e) - this.ResidualCapacities[e]);
            }
        }
Beispiel #19
0
        public void Walk(string nodeTypeNameToStart, Action <string, ToscaNodeType> action)
        {
            var breadthFirstSearchAlgorithm = new BreadthFirstSearchAlgorithm <string, ToscaGraphEdge>(graph);

            breadthFirstSearchAlgorithm.DiscoverVertex +=
                nodeTypeName => { action(nodeTypeName, nodeTypes[nodeTypeName]); };
            breadthFirstSearchAlgorithm.Compute(nodeTypeNameToStart);
        }
        public void ComputeWithRoot()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertex(0);
            var algorithm = new BreadthFirstSearchAlgorithm <int, Edge <int> >(graph);

            ComputeWithRoot_Test(algorithm);
        }
Beispiel #21
0
        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));
        }
Beispiel #22
0
        /// <summary>
        /// Computes the maximum flow between Source and Sink.
        /// </summary>
        protected override void InternalCompute()
        {
            if (Source == null)
            {
                throw new InvalidOperationException("Source is not specified.");
            }
            if (Sink == null)
            {
                throw new InvalidOperationException("Sink is not specified.");
            }

            if (Services.CancelManager.IsCancelling)
            {
                return;
            }

            var graph = VisitedGraph;

            foreach (TVertex vertex in graph.Vertices)
            {
                foreach (TEdge edge in graph.OutEdges(vertex))
                {
                    double capacity = Capacities(edge);
                    if (capacity < 0)
                    {
                        throw new InvalidOperationException("Negative edge capacity.");
                    }
                    ResidualCapacities[edge] = capacity;
                }
            }

            VerticesColors[Sink] = GraphColor.Gray;
            while (VerticesColors[Sink] != GraphColor.White)
            {
                var verticesPredecessors = new VertexPredecessorRecorderObserver <TVertex, TEdge>(Predecessors);
                var queue = new Queue <TVertex>();
                var bfs   = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(
                    ResidualGraph,
                    queue,
                    VerticesColors);

                using (verticesPredecessors.Attach(bfs))
                    bfs.Compute(Source);

                if (VerticesColors[Sink] != GraphColor.White)
                {
                    Augment(Source, Sink);
                }
            }

            MaxFlow = 0;
            foreach (TEdge edge in graph.OutEdges(Source))
            {
                MaxFlow += (Capacities(edge) - ResidualCapacities[edge]);
            }
        }
        public void BinarySearch_ValidItem()
        {
            var person = CreatePerson();
            var search = new BreadthFirstSearchAlgorithm();

            var result = search.SearchRobot(person);

            Assert.NotNull(result);
            Assert.Equal("Robot", result);
        }
        public void BlackTarget(Object sender, EdgeEventArgs args)
        {
            Assert.IsTrue(sender is BreadthFirstSearchAlgorithm);
            BreadthFirstSearchAlgorithm algo = (BreadthFirstSearchAlgorithm)sender;

            Assert.AreEqual(algo.Colors[args.Edge.Target], GraphColor.Black);

            foreach (IEdge e in algo.VisitedGraph.OutEdges(args.Edge.Target))
            {
                Assert.IsFalse(algo.Colors[e.Target] == GraphColor.White);
            }
        }
Beispiel #25
0
        public NeuralNetwork(AdjacencyGraph <INeuron, Connection> network, INeuron alphaVertex, INeuron omegaVertex)
        {
            _network    = network;
            AlphaVertex = alphaVertex;
            OmegaVertex = omegaVertex;

            _inputNeurons  = _network.OutEdges(AlphaVertex).Select(e => e.Target).ToList();
            _outputNeurons = _network.Edges.Where(e => e.Target == OmegaVertex).Select(e => e.Source).ToList();

            _algorithm              = new BreadthFirstSearchAlgorithm <INeuron, Connection>(_network);
            _algorithm.ExamineEdge += AddSignal;
            _algorithm.SetRootVertex(AlphaVertex);
        }
        public void TreeEdge(Object sender, EdgeEventArgs args)
        {
            Assert.IsTrue(sender is BreadthFirstSearchAlgorithm);
            BreadthFirstSearchAlgorithm algo = (BreadthFirstSearchAlgorithm)sender;

            IVertex u = args.Edge.Source;
            IVertex v = args.Edge.Target;

            Assert.AreEqual(algo.Colors[v], GraphColor.White);
            Assert.AreEqual(Distances[u], CurrentDistance);
            Parents[v]   = u;
            Distances[v] = Distances[u] + 1;
        }
Beispiel #27
0
        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));
        }
Beispiel #28
0
        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 Test2()
        {
            string chosenMap = @"
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 D 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    ";

            var map       = new Map(chosenMap);
            var algorithm = new BreadthFirstSearchAlgorithm(map.StartX, map.StartY, map.DestX, map.DestY, chosenMap);

            var sw     = System.Diagnostics.Stopwatch.StartNew();
            var result = algorithm.run();

            sw.Stop();
            Assert.IsTrue(sw.ElapsedMilliseconds < 100);
            System.Diagnostics.Debug.WriteLine("Elapsed: " + sw.ElapsedMilliseconds);

            result.Paths[0].NodeEquals(4, 10);

            result.Paths[1].NodeEquals(5, 10);
            result.Paths[2].NodeEquals(6, 10);
            result.Paths[3].NodeEquals(7, 10);
            result.Paths[4].NodeEquals(8, 10);
            result.Paths[5].NodeEquals(9, 10);
            result.Paths[6].NodeEquals(10, 10);
            result.Paths[7].NodeEquals(11, 10);
            result.Paths[8].NodeEquals(12, 10);
            result.Paths[9].NodeEquals(13, 10);
            result.Paths[10].NodeEquals(14, 10);
            result.Paths[11].NodeEquals(15, 10);
            result.Paths[12].NodeEquals(16, 10);
            result.Paths[13].NodeEquals(17, 10);
        }
Beispiel #30
0
        /// <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);
        }