コード例 #1
0
        public List <string> ApproximateWith2Approximation(
            UndirectedGraph <string, TaggedUndirectedEdge <string, int> > pUndirectedCompletedGraph, string pStartVertex)
        {
            List <string> verticePath = new List <string>();

            var minimumSpanningTree = pUndirectedCompletedGraph.MinimumSpanningTreePrim(e => e.Tag).ToList();

            var minimumSpanningTreeGraph = new UndirectedGraph <string, TaggedUndirectedEdge <string, int> >();

            minimumSpanningTreeGraph.AddVerticesAndEdgeRange(minimumSpanningTree);

            var depthFirstSearch = new UndirectedDepthFirstSearchAlgorithm <string, TaggedUndirectedEdge <string, int> >(minimumSpanningTreeGraph);

            depthFirstSearch.DiscoverVertex += delegate(string vertex) {
                if (!verticePath.Contains(vertex))
                {
                    verticePath.Add(vertex);
                }
            };

            depthFirstSearch.Compute(pStartVertex);

            verticePath.Add(pStartVertex);

            return(verticePath);
        }
コード例 #2
0
        protected override void InternalCompute()
        {
            this.components.Clear();
            if (this.VisitedGraph.VertexCount == 0)
            {
                this.componentCount = 0;
                return;
            }

            this.componentCount = -1;
            UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> dfs = null;

            try
            {
                dfs = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(
                    this,
                    this.VisitedGraph,
                    new Dictionary <TVertex, GraphColor>(this.VisitedGraph.VertexCount)
                    );

                dfs.StartVertex    += new VertexAction <TVertex>(this.StartVertex);
                dfs.DiscoverVertex += new VertexAction <TVertex>(this.DiscoverVertex);
                dfs.Compute();
                ++this.componentCount;
            }
            finally
            {
                if (dfs != null)
                {
                    dfs.StartVertex    -= new VertexAction <TVertex>(this.StartVertex);
                    dfs.DiscoverVertex -= new VertexAction <TVertex>(this.DiscoverVertex);
                }
            }
        }
コード例 #3
0
        public void SetRootVertex_Throws()
        {
            var graph     = new UndirectedGraph <TestVertex, Edge <TestVertex> >();
            var algorithm = new UndirectedDepthFirstSearchAlgorithm <TestVertex, Edge <TestVertex> >(graph);

            SetRootVertex_Throws_Test(algorithm);
        }
コード例 #4
0
        /// <inheritdoc />
        protected override void InternalCompute()
        {
            UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> dfs = null;

            try
            {
                dfs = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(
                    this,
                    VisitedGraph,
                    new Dictionary <TVertex, GraphColor>(VisitedGraph.VertexCount));
                dfs.BackEdge     += BackEdge;
                dfs.FinishVertex += OnVertexFinished;

                dfs.Compute();
            }
            finally
            {
                if (dfs != null)
                {
                    dfs.BackEdge     -= BackEdge;
                    dfs.FinishVertex -= OnVertexFinished;

                    SortedVertices = _sortedVertices.Reverse().ToArray();
                }
            }
        }
コード例 #5
0
        protected override void InternalCompute()
        {
            UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> dfs = null;

            try
            {
                dfs = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(
                    this,
                    VisitedGraph,
                    new Dictionary <TVertex, GraphColor>(this.VisitedGraph.VertexCount)
                    );
                dfs.BackEdge     += BackEdge;
                dfs.FinishVertex += FinishVertex;

                dfs.Compute();
            }
            finally
            {
                if (dfs != null)
                {
                    dfs.BackEdge     -= BackEdge;
                    dfs.FinishVertex -= FinishVertex;
                }
            }
        }
コード例 #6
0
        public void ClearRootVertex()
        {
            var graph     = new UndirectedGraph <int, Edge <int> >();
            var algorithm = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph);

            ClearRootVertex_Test(algorithm);
        }
コード例 #7
0
        public void StartVertex(Object sender, VertexEventArgs args)
        {
            Assert.IsTrue(sender is UndirectedDepthFirstSearchAlgorithm);
            UndirectedDepthFirstSearchAlgorithm algo = (UndirectedDepthFirstSearchAlgorithm)sender;

            Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.White);
        }
コード例 #8
0
        /// <inheritdoc />
        protected override void InternalCompute()
        {
            if (VisitedGraph.VertexCount == 0)
            {
                return;
            }

            ComponentCount = -1;
            UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> dfs = null;

            try
            {
                dfs = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(
                    this,
                    VisitedGraph,
                    new Dictionary <TVertex, GraphColor>(VisitedGraph.VertexCount));

                dfs.StartVertex    += OnStartVertex;
                dfs.DiscoverVertex += OnVertexDiscovered;
                dfs.Compute();
                ++ComponentCount;
            }
            finally
            {
                if (dfs != null)
                {
                    dfs.StartVertex    -= OnStartVertex;
                    dfs.DiscoverVertex -= OnVertexDiscovered;
                }
            }
        }
コード例 #9
0
        private void RunDFS(UndirectedGraph <int, UndirectedEdge <int> > graph)
        {
            var dfs = new UndirectedDepthFirstSearchAlgorithm <int, UndirectedEdge <int> >(graph);

            dfs.TreeEdge += (s, e) => vertex.Add(e.Target);
            dfs.Compute(0);
        }
コード例 #10
0
        public void FinishVertex(Object sender, VertexEventArgs args)
        {
            Assert.IsTrue(sender is UndirectedDepthFirstSearchAlgorithm);
            UndirectedDepthFirstSearchAlgorithm algo = (UndirectedDepthFirstSearchAlgorithm)sender;

            Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.Black);
            FinishTimes[args.Vertex] = time++;
        }
コード例 #11
0
        public static IEnumerable <TEdge> LongestPathBruteDepthFirst <TVertex, TEdge>
        (
            this UndirectedGraph <TVertex, TEdge> graph,
            Func <TEdge, double> getEdgeWeight
        )
            where TEdge : IEdge <TVertex>
        {
            var search   = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(graph);
            var bestPath = new TEdge[0];
            var bestSum  = 0d;

            foreach (var vertex in graph.Vertices)
            {
                if (bestPath.Any() && new[] { bestPath.First(), bestPath.Last() }.Any(r => r.Source.Equals(vertex) || r.Target.Equals(vertex)))
                {
                    continue;
                }

                var currentPath = new Stack <TEdge>();
                var currentSum  = 0d;

                Action unCount = () =>
                {
                    if (currentPath.Any())
                    {
                        var edge = currentPath.Pop();
                        currentSum -= getEdgeWeight(edge);
                    }
                };

                UndirectedEdgeAction <TVertex, TEdge> countEdge = (sender, args) =>
                {
                    currentPath.Push(args.Edge);
                    currentSum += getEdgeWeight(args.Edge);

                    if (currentSum > bestSum)
                    {
                        bestPath = currentPath.ToArray();
                        bestSum  = currentSum;
                    }
                };

                UndirectedEdgeAction <TVertex, TEdge> countUncountEdge = (sender, args) =>
                {
                    countEdge(sender, args);
                    unCount();
                };

                search.TreeEdge           += countEdge;
                search.ForwardOrCrossEdge += countUncountEdge;
                search.BackEdge           += countUncountEdge;
                search.FinishVertex       += delegate { unCount(); };

                search.Compute(vertex);
            }

            return(bestPath);
        }
        public void TryGetPath()
        {
            {
                var recorder = new UndirectedVertexPredecessorRecorderObserver <int, Edge <int> >();

                var graph = new UndirectedGraph <int, Edge <int> >();

                var dfs = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    // Vertex not in the graph
                    Assert.IsFalse(recorder.TryGetPath(2, out _));
                }
            }

            {
                var recorder = new UndirectedVertexPredecessorRecorderObserver <int, Edge <int> >();

                var graph = new UndirectedGraph <int, Edge <int> >();
                graph.AddVertexRange(new[] { 1, 2 });

                var dfs = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    Assert.IsFalse(recorder.TryGetPath(2, out _));
                }
            }

            {
                var recorder = new UndirectedVertexPredecessorRecorderObserver <int, Edge <int> >();

                var edge12 = new Edge <int>(1, 2);
                var edge14 = new Edge <int>(1, 4);
                var edge31 = new Edge <int>(3, 1);
                var edge33 = new Edge <int>(3, 3);
                var edge34 = new Edge <int>(3, 4);
                var edge42 = new Edge <int>(4, 2);
                var graph  = new UndirectedGraph <int, Edge <int> >();
                graph.AddVerticesAndEdgeRange(new[]
                {
                    edge12, edge14, edge31, edge33, edge34, edge42
                });

                var dfs = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    Assert.IsTrue(recorder.TryGetPath(4, out IEnumerable <Edge <int> > path));
                    CollectionAssert.AreEqual(new[] { edge12, edge42 }, path);
                }
            }
        }
コード例 #13
0
        public void ComputeWithRoot()
        {
            var graph = new UndirectedGraph <int, Edge <int> >();

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

            ComputeWithRoot_Test(algorithm);
        }
コード例 #14
0
    //public bool status;

    void Start()
    {
        dfs    = new UndirectedDepthFirstSearchAlgorithm <string, UndirectedEdge <string> >(AirSystem.graphAir);
        output = GetComponentInChildren <CreateVertex>();

        canv   = this.transform.Find("Canvas").GetComponent <Canvas>();
        slider = canv.GetComponentInChildren <Slider>();

        airSystem = GameObject.Find("PneumaticSystem").GetComponent <AirSystem>();
    }
コード例 #15
0
        public void ExamineEdge(Object sender, EdgeEventArgs args)
        {
            Assert.IsTrue(sender is UndirectedDepthFirstSearchAlgorithm);
            UndirectedDepthFirstSearchAlgorithm algo = (UndirectedDepthFirstSearchAlgorithm)sender;

            bool sourceGray = algo.Colors[args.Edge.Source] == GraphColor.Gray;
            bool targetGray = algo.Colors[args.Edge.Target] == GraphColor.Gray;

            Assert.IsTrue(sourceGray || targetGray);
        }
コード例 #16
0
        public void DiscoverVertex(Object sender, VertexEventArgs args)
        {
            Assert.IsTrue(sender is UndirectedDepthFirstSearchAlgorithm);
            UndirectedDepthFirstSearchAlgorithm algo = (UndirectedDepthFirstSearchAlgorithm)sender;

            Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.Gray);
            Assert.AreEqual(algo.Colors[Parents[args.Vertex]], GraphColor.Gray);

            DiscoverTimes[args.Vertex] = time++;
        }
コード例 #17
0
        public static IDictionary <int, double> Get(UndirectedGraph <int, Edge <int> > g)
        {
            var dfs      = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(g);
            var recorder = new UndirectedVertexDistanceRecorderObserver <int, Edge <int> >(edgeWeights => 1.0);

            using (recorder.Attach(dfs))
            {
                dfs.Compute();
                return(recorder.Distances);
            }
        }
コード例 #18
0
        public static IDictionary <string, double> Get(UndirectedGraph <string, TaggedEdge <string, string> > g)
        {
            var dfs      = new UndirectedDepthFirstSearchAlgorithm <string, TaggedEdge <string, string> >(g);
            var recorder = new UndirectedVertexDistanceRecorderObserver <string, TaggedEdge <string, string> >(edgeWeights => double.Parse(edgeWeights.Tag));

            using (recorder.Attach(dfs))
            {
                dfs.Compute();
                return(recorder.Distances);
            }
        }
コード例 #19
0
        public static IDictionary <int, Edge <int> > Get(UndirectedGraph <int, Edge <int> > g)
        {
            var dfs      = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(g);
            var recorder = new UndirectedVertexPredecessorRecorderObserver <int, Edge <int> >();

            using (recorder.Attach(dfs))
            {
                dfs.Compute();
                return(recorder.VerticesPredecessors);
            }
        }
コード例 #20
0
        public static IEnumerable <TaggedEdge <string, string> > GetPath(UndirectedGraph <string, TaggedEdge <string, string> > g, string v)
        {
            var dfs      = new UndirectedDepthFirstSearchAlgorithm <string, TaggedEdge <string, string> >(g);
            var recorder = new UndirectedVertexPredecessorRecorderObserver <string, TaggedEdge <string, string> >();

            using (recorder.Attach(dfs))
            {
                dfs.Compute();
                recorder.TryGetPath(v, out var path);
                return(path);
            }
        }
コード例 #21
0
        public void Compute()
        {
            this.joins.Clear();
            this.startVertex = null;
            UndirectedDepthFirstSearchAlgorithm udfs =
                new UndirectedDepthFirstSearchAlgorithm(this.VisitedGraph);

            udfs.TreeEdge    += new EdgeEventHandler(udfs_TreeEdge);
            udfs.StartVertex += new VertexEventHandler(udfs_StartVertex);

            udfs.Compute();
        }
コード例 #22
0
        public void Constructor()
        {
            var graph     = new UndirectedGraph <int, Edge <int> >();
            var algorithm = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph);

            AssertAlgorithmProperties(algorithm, graph);

            var verticesColors = new Dictionary <int, GraphColor>();

            algorithm = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph, verticesColors);
            AssertAlgorithmProperties(algorithm, graph, verticesColors);

            algorithm = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(null, graph, verticesColors);
            AssertAlgorithmProperties(algorithm, graph, verticesColors);

            algorithm = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(null, graph, verticesColors, edges => edges.Where(e => e != null));
            AssertAlgorithmProperties(algorithm, graph, verticesColors);

            algorithm.MaxDepth = 12;
            AssertAlgorithmProperties(algorithm, graph, verticesColors, 12);

            algorithm.ProcessAllComponents = true;
            AssertAlgorithmProperties(algorithm, graph, verticesColors, 12, true);

            #region Local function

            void AssertAlgorithmProperties <TVertex, TEdge>(
                UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> algo,
                IUndirectedGraph <TVertex, TEdge> g,
                IDictionary <TVertex, GraphColor> vColors = null,
                int maxDepth = int.MaxValue,
                bool processAllComponents = false)
                where TEdge : IEdge <TVertex>
            {
                AssertAlgorithmState(algo, g);
                if (vColors is null)
                {
                    CollectionAssert.IsEmpty(algo.VerticesColors);
                }
                else
                {
                    Assert.AreSame(vColors, algo.VerticesColors);
                }
                Assert.AreEqual(maxDepth, algo.MaxDepth);
                Assert.AreEqual(processAllComponents, algo.ProcessAllComponents);
                Assert.IsNotNull(algo.AdjacentEdgesFilter);
            }

            #endregion
        }
コード例 #23
0
        public UndirectedTopologicalSortAlgorithm(
            IUndirectedGraph <TVertex, TEdge> g,
            IList <TVertex> vertices)
            : base(g)
        {
            if (vertices == null)
            {
                throw new ArgumentNullException("vertices");
            }

            this.vertices          = vertices;
            this.dfs               = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
            this.dfs.BackEdge     += new EdgeEventHandler <TVertex, TEdge>(this.BackEdge);
            this.dfs.FinishVertex += new VertexEventHandler <TVertex>(this.FinishVertex);
        }
コード例 #24
0
        public void Init()
        {
            parents       = new VertexVertexDictionary();
            discoverTimes = new VertexIntDictionary();
            finishTimes   = new VertexIntDictionary();
            time          = 0;
            g             = new BidirectionalGraph(true);
            dfs           = new UndirectedDepthFirstSearchAlgorithm(g);

            dfs.StartVertex    += new VertexEventHandler(this.StartVertex);
            dfs.DiscoverVertex += new VertexEventHandler(this.DiscoverVertex);
            dfs.ExamineEdge    += new EdgeEventHandler(this.ExamineEdge);
            dfs.TreeEdge       += new EdgeEventHandler(this.TreeEdge);
            dfs.BackEdge       += new EdgeEventHandler(this.BackEdge);
            dfs.FinishVertex   += new VertexEventHandler(this.FinishVertex);
        }
コード例 #25
0
ファイル: Board.cs プロジェクト: vfridell/HiveLib
        /// <summary>
        /// An articulation point is a hex with a piece whose removal
        /// causes a violation of the one-hive rule.
        /// </summary>
        private void FindArticulationPoints()
        {
            _articulationPoints.Clear();
            _adjacencyGraph.RemoveEdgeIf(e => e.Source == e.Target);
            var dfs = new UndirectedDepthFirstSearchAlgorithm <Piece, UndirectedEdge <Piece> >(_adjacencyGraph);
            var articulationPointObserver = new HiveLib.Helpers.UndirectedArticulationPointObserver <Piece, UndirectedEdge <Piece> >(_articulationPoints);

            using (articulationPointObserver.Attach(dfs))
            {
                if (_playedPieces.Count > 2)
                {
                    Piece root = _playedPieces.Keys.First();
                    dfs.Compute(root);
                }
            }
        }
コード例 #26
0
        public ConnectedComponentsAlgorithm(
            IUndirectedGraph <TVertex, TEdge> visitedGraph,
            IDictionary <TVertex, int> components)
            : base(visitedGraph)
        {
            if (components == null)
            {
                throw new ArgumentNullException("components");
            }

            this.components = components;
            dfs             = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>(visitedGraph);

            dfs.StartVertex    += new VertexEventHandler <TVertex>(this.StartVertex);
            dfs.DiscoverVertex += new VertexEventHandler <TVertex>(this.DiscoverVertex);
        }
コード例 #27
0
        public IDisposable Attach(UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> algorithm)
        {
            algorithm.DiscoverVertex += dfs_DiscoverVertex;
            algorithm.FinishVertex   += dfs_FinishVertex;
            algorithm.BackEdge       += dfs_BackEdge;
            algorithm.TreeEdge       += dfs_TreeEdge;

            return(new DisposableAction(
                       () =>
            {
                algorithm.DiscoverVertex -= new VertexAction <TVertex>(dfs_DiscoverVertex);
                algorithm.FinishVertex -= new VertexAction <TVertex>(dfs_FinishVertex);
                algorithm.BackEdge -= new UndirectedEdgeAction <TVertex, TEdge>(dfs_BackEdge);
                algorithm.TreeEdge -= new UndirectedEdgeAction <TVertex, TEdge>(dfs_TreeEdge);
            }));
        }
コード例 #28
0
        public static UndirectedDepthFirstSearchAlgorithm <T, Edge <T> > CreateAlgorithmAndMaybeDoComputation <T>(
            ContractScenario <T> scenario)
        {
            var graph = new UndirectedGraph <T, Edge <T> >();

            graph.AddVerticesAndEdgeRange(scenario.EdgesInGraph.Select(e => new Edge <T>(e.Source, e.Target)));
            graph.AddVertexRange(scenario.SingleVerticesInGraph);

            var algorithm = new UndirectedDepthFirstSearchAlgorithm <T, Edge <T> >(graph);

            if (scenario.DoComputation)
            {
                algorithm.Compute(scenario.Root);
            }
            return(algorithm);
        }
コード例 #29
0
        public void GetVertexColor()
        {
            var graph = new UndirectedGraph <int, Edge <int> >();

            graph.AddVerticesAndEdge(new Edge <int>(1, 2));

            var algorithm = new UndirectedDepthFirstSearchAlgorithm <int, Edge <int> >(graph);

            // Algorithm not run
            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Assert.Throws <VertexNotFoundException>(() => algorithm.GetVertexColor(1));

            algorithm.Compute();

            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(1));
            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(2));
        }
コード例 #30
0
    private void Start()
    {
        // Получение компонентов вершин
        //
        input   = transform.Find("Input").GetComponent <CreateVertex>();
        output1 = transform.Find("Output 1").GetComponent <CreateVertex>();
        output2 = transform.Find("Output 2").GetComponent <CreateVertex>();
        //

        // Получение компонента сладйера
        //
        canv   = this.transform.Find("Canvas").GetComponent <Canvas>();
        slider = canv.GetComponentInChildren <Slider>();
        //

        dfs       = new UndirectedDepthFirstSearchAlgorithm <string, UndirectedEdge <string> >(AirSystem.graphAir);
        airSystem = GameObject.Find("PneumaticSystem").GetComponent <AirSystem>();
    }