Пример #1
8
        public void test1()
        {
            UndirectedGraph<int, Edge<int>> graph = new UndirectedGraph<int, Edge<int>>(true);

            // Add vertices to the graph
            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            // Create the edges
            Edge<int> e0_1 = new Edge<int>(0, 1);
            Edge<int> e0_2 = new Edge<int>(0, 2);
            Edge<int> e1_2 = new Edge<int>(1, 2);
            Edge<int> e1_3 = new Edge<int>(1, 3);
            // Add the edges
            graph.AddEdge(e0_1);
            graph.AddEdge(e0_2);
            graph.AddEdge(e1_2);
            graph.AddEdge(e1_3);

            List<int> path = new List<int>();

            HamiltonianDefiner definer = new HamiltonianDefiner(graph);
            bool isHamiltonian = definer.isHamiltonianGraph(path);
            Assert.AreEqual(isHamiltonian, false);
        }
Пример #2
0
        public void FindShortestPathForSimpleUndirectedGraphUsingDijkstraAlgorithm()
        {
            var graph = new UndirectedGraph<object, Edge<object>>(true);
            object v1 = "vertex1";
            object v2 = "vertex2";
            object v3 = "vertex3";
            var e1 = new Edge<object>(v1, v2);
            var e2 = new Edge<object>(v2, v3);
            var e3 = new Edge<object>(v3, v1);
            graph.AddVertex(v1);
            graph.AddVertex(v2);
            graph.AddVertex(v3);
            graph.AddEdge(e1);
            graph.AddEdge(e2);
            graph.AddEdge(e3);

            var algorithm = new UndirectedDijkstraShortestPathAlgorithm<object, Edge<object>>(graph, edge => (double)1);
            var observer = new UndirectedVertexPredecessorRecorderObserver<object, Edge<object>>();
            using (observer.Attach(algorithm))
            {
                algorithm.Compute(v1);
            }

            IEnumerable<Edge<object>> path;
            observer.TryGetPath(v3, out path);

            foreach (var edge in path)
            {
                Console.WriteLine(edge);
            }
        }
Пример #3
0
        // effects: Given a list of cells, segments them into multiple
        // "groups" such that view generation (including validation) of one
        // group can be done independently of another group. Returns the
        // groups as a list (uses the foreign key information as well)
        internal List<CellGroup> GroupRelatedCells()
        {
            // If two cells share the same C or S, we place them in the same group
            // For each cell, determine the Cis and Sis that it refers
            // to. For every Ci (Si), keep track of the cells that Ci is
            // contained in. At the end, run through the Cis and Sis and do a
            // "connected components" algorithm to determine partitions

            var extentGraph = new UndirectedGraph<EntitySetBase>(EqualityComparer<EntitySetBase>.Default);
            var extentToCell = new Dictionary<EntitySetBase, Set<Cell>>(EqualityComparer<EntitySetBase>.Default);

            foreach (var cell in m_cells)
            {
                foreach (var extent in new[] { cell.CQuery.Extent, cell.SQuery.Extent })
                {
                    Set<Cell> cellsWithExtent;
                    if (!extentToCell.TryGetValue(extent, out cellsWithExtent))
                    {
                        extentToCell[extent] = cellsWithExtent = new Set<Cell>();
                    }
                    cellsWithExtent.Add(cell);
                    extentGraph.AddVertex(extent);
                }
                extentGraph.AddEdge(cell.CQuery.Extent, cell.SQuery.Extent);

                var associationSetExtent = cell.CQuery.Extent as AssociationSet;
                if (associationSetExtent != null)
                {
                    foreach (var end in associationSetExtent.AssociationSetEnds)
                    {
                        extentGraph.AddEdge(end.EntitySet, associationSetExtent);
                    }
                }
            }

            foreach (var fk in m_foreignKeyConstraints)
            {
                extentGraph.AddEdge(fk.ChildTable, fk.ParentTable);
            }

            var groupMap = extentGraph.GenerateConnectedComponents();
            var result = new List<CellGroup>();
            foreach (var setNum in groupMap.Keys)
            {
                var cellSets = groupMap.ListForKey(setNum).Select(e => extentToCell[e]);
                var component = new CellGroup();
                foreach (var cellSet in cellSets)
                {
                    component.AddRange(cellSet);
                }

                result.Add(component);
            }

            return result;
        }
Пример #4
0
        public void AddEdge_Test()
        {
            var ug = new UndirectedGraph(10);

            ug.AddEdge(4, 0);
            ug.AddEdge(4, 3);
            ug.AddEdge(4, 7);

            Assert.AreEqual(3, ug.E);
        }
        public static void Main()
        {
            var graph = new UndirectedGraph<int, Edge<int>>();

            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);

            graph.AddEdge(new Edge<int>(1, 2));
            graph.AddEdge(new Edge<int>(3, 4));
            graph.AddEdge(new Edge<int>(1, 4));

            foreach (var edge in graph.Edges)
            {
                Console.WriteLine(edge.Source + " " + edge.Target);
            }
        }
    public static void Main()
    {
        // ot Manage NuGet Packages- izpolzvame vanshna biblioteka;
        // https://quickgraph.codeplex.com/documentation
        var graph = new UndirectedGraph<int, Edge<int>>();

        graph.AddVertex(1);
        graph.AddVertex(2);
        graph.AddVertex(3);
        graph.AddVertex(4);

        graph.AddEdge(new Edge<int>(1, 2));
        graph.AddEdge(new Edge<int>(3, 4));
        graph.AddEdge(new Edge<int>(1, 4));

        foreach (var edge in graph.Edges)
        {
            Console.WriteLine(edge.Source + " " + edge.Target);
        }
    }
Пример #7
0
        static void Main(string[] args)
        {
            UndirectedGraph<int, Edge<int>> graph = new UndirectedGraph<int, Edge<int>>(true);

            // Add vertices to the graph
            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);
            graph.AddVertex(5);
            // Create the edges
            Edge<int> e0_1 = new Edge<int>(0, 1);
            Edge<int> e0_2 = new Edge<int>(0, 2);
            Edge<int> e1_2 = new Edge<int>(1, 2);
            Edge<int> e3_4 = new Edge<int>(3, 4);
            Edge<int> e4_5 = new Edge<int>(4, 5);
            Edge<int> e3_5 = new Edge<int>(3, 5);
            // Add the edges
            graph.AddEdge(e0_1);
            graph.AddEdge(e0_2);
            graph.AddEdge(e1_2);
            graph.AddEdge(e3_4);
            graph.AddEdge(e4_5);
            graph.AddEdge(e3_5);

            List<int> path = new List<int>();

            HamiltonianDefiner definer = new HamiltonianDefiner(graph);
            bool isHamiltonian = definer.isHamiltonianGraph(path);
            Console.WriteLine(isHamiltonian);
            Console.ReadLine();
        }
        // effects: Given a list of cells, segments them into multiple
        // "groups" such that view generation (including validation) of one
        // group can be done independently of another group. Returns the
        // groups as a list (uses the foreign key information as well)
        internal List<CellGroup> GroupRelatedCells()
        {
            // If two cells share the same C or S, we place them in the same group
            // For each cell, determine the Cis and Sis that it refers
            // to. For every Ci (Si), keep track of the cells that Ci is
            // contained in. At the end, run through the Cis and Sis and do a
            // "connected components" algorithm to determine partitions

            // Now form a graph between different cells -- then compute the connected
            // components in it
            var graph = new UndirectedGraph<Cell>(EqualityComparer<Cell>.Default);

            var alreadyAddedCells = new List<Cell>();
            // For each extent, add an edge between it and all previously
            // added extents with which it overlaps

            foreach (var cell in m_cells)
            {
                graph.AddVertex(cell);
                // Add an edge from this cell to the already added cells
                var firstCExtent = cell.CQuery.Extent;
                var firstSExtent = cell.SQuery.Extent;
                foreach (var existingCell in alreadyAddedCells)
                {
                    var secondCExtent = existingCell.CQuery.Extent;
                    var secondSExtent = existingCell.SQuery.Extent;

                    // Add an edge between cell and existingCell if
                    // * They have the same C or S extent
                    // * They are linked via a foreign key between the S extents
                    // * They are linked via a relationship
                    var sameExtent = secondCExtent.Equals(firstCExtent) || secondSExtent.Equals(firstSExtent);
                    var linkViaForeignKey = OverlapViaForeignKeys(cell, existingCell);
                    var linkViaRelationship = AreCellsConnectedViaRelationship(cell, existingCell);

                    if (sameExtent || linkViaForeignKey || linkViaRelationship)
                    {
                        graph.AddEdge(existingCell, cell);
                    }
                }
                alreadyAddedCells.Add(cell);
            }

            // Now determine the connected components of this graph
            var result = GenerateConnectedComponents(graph);
            return result;
        }
Пример #9
0
        public void RemoveVertexFromNonEmptyGraphTest()
        {
            var graph      = new UndirectedGraph();
            var newVertex1 = new Vertex("test-1");
            var newVertex2 = new Vertex("test-2");

            graph.AddVertex(newVertex1);
            graph.AddVertex(newVertex2);
            var edge = new UndirectedEdge(newVertex1, newVertex2);

            graph.AddEdge(edge);

            Assert.DoesNotThrow(() => graph.RemoveVertex(newVertex1));
            Assert.AreEqual(graph.VerticesCount, 1);
            Assert.AreEqual(graph.EdgesCount, 0);
            Assert.IsTrue(graph.Vertices.Contains(newVertex2));
        }
Пример #10
0
    public static void TestVertexDisjointPath1(bool log = true, int loops = 1000)
    {
        for (int loop = 0; loop < loops; ++loop)
        {
            var g        = new UndirectedGraph <int>();
            var rnd      = new Random();
            int vertices = 10 + rnd.Next(1000);
            int edges    = vertices / 2 + rnd.Next(vertices * vertices / 4);
            for (int i = 0; i < edges; ++i)
            {
                int start = rnd.Next(vertices);
                int end   = rnd.Next(vertices);
                if (start != end)
                {
                    g.AddEdge(start, end);
                }
            }
            g.RemoveEdge(0, vertices - 1); // Remove trivial path!
            if (log)
            {
                Console.WriteLine(g);
            }

            var paths        = g.FindVertexDisjointPaths(0, vertices - 1);
            var usedVertices = CheckVDP(g, paths, log);
            // Find a cut
            var cut = g.FindCutVDP(0, paths);
            if (log)
            {
                Console.WriteLine("Size of cut: {0}", cut.Count());
            }
            if (paths.Count() != cut.Count())
            {
                throw new Exception("Cut and disjoint path count differ.");
            }
            foreach (var v in cut)
            {
                g.RemoveVertex(v);
            }
            if (g.FindPath(0, vertices - 1).Count() > 0)
            {
                Console.WriteLine(g);
                throw new Exception("Graph not disconnected!");
            }
        }
    }
Пример #11
0
        public static Tuple <int, HashSet <Edge <int> > > RunWithKernel(UndirectedGraph <int, Edge <int> > graph)
        {
            //DrawGraph.drawGraph(graph, new HashSet<Edge<int>>(), @"C:\Users\Frederik\Desktop\a.dot");
            var componentAlgorithm = new QuickGraph.Algorithms.ConnectedComponents.ConnectedComponentsAlgorithm <int, Edge <int> >(graph);

            componentAlgorithm.Compute();
            var nodeToComponent = componentAlgorithm.Components;
            var time            = DateTime.Now;
            var retk            = 0;
            var retEdges        = new HashSet <Edge <int> >();

            for (int i = 0; i < componentAlgorithm.ComponentCount; i++)
            {
                var g = new UndirectedGraph <int, Edge <int> >(false);
                foreach (var v in graph.Vertices)
                {
                    if (nodeToComponent[v] == i)
                    {
                        g.AddVertex(v);
                    }
                }
                foreach (var v in g.Vertices)
                {
                    foreach (var e in graph.AdjacentEdges(v))
                    {
                        g.AddEdge(e);
                    }
                }

                var kernel = Kernel.Init(CloneGraph(g)); //remember to clone graph, as the phases will "butcher" the graph.
                var tup    = FindKKernel(g, time, kernel);
                var k      = tup.Item1;
                var edges  = tup.Item2;
                retk += k;
                foreach (var e in edges)
                {
                    retEdges.Add(e);
                }
            }
            var clone2 = CloneGraph(graph);

            clone2.AddEdgeRange(retEdges);
            //DrawGraph.drawGraph(clone2, retEdges, @"C:\Users\Frederik\Desktop\b.dot");
            return(new Tuple <int, HashSet <Edge <int> > >(retk, retEdges));
        }
Пример #12
0
        public void RemoveEdgeTest()
        {
            var graph   = new UndirectedGraph();
            var vertex1 = new Vertex("test-1");
            var vertex2 = new Vertex("test-2");

            graph.AddVertex(vertex1);
            graph.AddVertex(vertex2);
            var edge = new UndirectedEdge(vertex1, vertex2);

            graph.AddEdge(edge);
            Assert.DoesNotThrow(() => graph.RemoveEdge(edge));
            Assert.AreEqual(graph.EdgesCount, 0);
            Assert.IsNull(graph[vertex1, vertex2]);
            Assert.IsNull(graph[vertex2, vertex1]);
            Assert.Throws <InvalidOperationException>(() => graph.RemoveEdge(edge));
            Assert.Throws <ArgumentNullException>(() => graph.RemoveEdge(null));
        }
Пример #13
0
        public void Bipartite()
        {
            var graph = new UndirectedGraph <char, EdgeData>();

            graph.AddNodes('a', 'b', 'c', 'd', 'e');
            graph.AddEdges(
                ('a', 'b', dummyEdgeData),
                ('a', 'c', dummyEdgeData),
                ('b', 'd', dummyEdgeData),
                ('c', 'e', dummyEdgeData)
                );

            graph.Bipartite.Should().BeTrue();

            graph.AddEdge('a', 'e', dummyEdgeData);

            graph.Bipartite.Should().BeFalse();
        }
Пример #14
0
        public static void RhinoBFS(List <int> N, List <int> U, List <int> V, List <double> W = null)
        {
            //Create undirected graph
            UndirectedGraph <int, Edge <int> > g = new UndirectedGraph <int, Edge <int> >();

            g.AddVertexRange(N);
            for (int i = 0; i < U.Count; i++)
            {
                g.AddEdge(new QuickGraph.Edge <int>(U[i], V[i]));
            }

            //BFS
            var bfs = new QuickGraph.Algorithms.Search.UndirectedBreadthFirstSearchAlgorithm <int, QuickGraph.Edge <int> >(g);

            var observer = new VertexPredecessorRecorderObserver <int, QuickGraph.Edge <int> >();
            //using (ObserverScope.Create(bfs, observer)) // attach, detach to dfs events
            //bfs.Compute();
        }
        private UndirectedGraph<int, int> GetGraph(int noOfNodes, int maxNoOfEdges)
        {
            var startTime = DateTime.UtcNow;
            var graph = new UndirectedGraph<int, int>();
            var e = 0;
            for (int n = 1; n <= noOfNodes && e<= maxNoOfEdges; n++)
            {
                for (int i = n + 1; i <= noOfNodes && e <= maxNoOfEdges; i++, e++)
                {
                    graph.AddEdge(n, i, 1);
                }

            }

            var endTime = DateTime.UtcNow;
            System.Diagnostics.Trace.WriteLine(String.Format("Completed graph construction in {0}",endTime. Subtract(startTime).TotalMilliseconds));
            return graph;
        }
Пример #16
0
        public static bool TryParseFile(string inputLine, out UndirectedGraph <int, Edge <int> > graph, out List <Tuple <int, int> > edgesList)
        {
            UndirectedGraph <int, Edge <int> > g = new UndirectedGraph <int, Edge <int> >(false);
            int lineCounter    = 0;
            int numberOfPeople = 0;
            int pairsNumber    = 0;
            var lines          = System.IO.File.ReadAllLines(inputLine);

            edgesList = new List <Tuple <int, int> >();
            foreach (string line in lines)
            {
                if (lineCounter == 0)
                {
                    ParseSingleInteger(line, out numberOfPeople);
                    for (int i = 0; i < numberOfPeople; i++)
                    {
                        g.AddVertex(i);
                    }
                }
                else if (lineCounter == 1)
                {
                    ParseSingleInteger(line, out pairsNumber);
                }
                else
                {
                    if (lineCounter - 2 > pairsNumber)
                    {
                        Console.WriteLine("Reading lines done");
                        break;
                    }

                    var pair = ParsePairLine(line);
                    edgesList.Add(pair);

                    // not needed (?)
                    g.AddEdge(new Edge <int>(pair.Item1, pair.Item2));
                }
                lineCounter++;
            }

            graph = CreateFinalGraph(numberOfPeople, edgesList);

            return(true);
        }
Пример #17
0
        /// <summary>
        /// Schedule execution of transaction
        /// </summary>
        void Scheduler()
        {
            //  Execution strategy(experimental)
            //  1. tranform the dependency of Resource(R) into graph of related Transactions(T)
            //  2. find the T(ransaction) which connects to the most neightbours
            //  3. execute the T(ransaction), and removes this node from the graph
            //  4. check to see if this removal leads to graph split
            //  5. if YES, we can parallel execute the transactions from the splitted graph
            //  6  if NO, goto step 2

            // build the graph
            UndirectedGraph <IHash, Edge <IHash> > graph = new UndirectedGraph <IHash, Edge <IHash> >(false);

            this.mut.WaitOne();
            foreach (var grp in pending)
            {
                foreach (var tx in grp.Value)
                {
                    if (graph.ContainsVertex(tx.GetHash()))
                    {
                        continue;
                    }
                    graph.AddVertex(tx.GetHash());
                }

                foreach (var tx in grp.Value)
                {
                    foreach (var neighbour in grp.Value)
                    {
                        if (!tx.Equals(neighbour))
                        {
                            graph.AddEdge(new Edge <IHash>(tx.GetHash(), neighbour.GetHash()));
                        }
                    }
                }
            }

            ExecuteGraph(graph);
            // reset
            pending = new Dictionary <IHash, List <ITransaction> >();
            this.mut.ReleaseMutex();

            // TODO: parallel execution on root nodes;
        }
Пример #18
0
    // Tricky part is noticing that instead of words being vertices, words can be edges in
    // a graph whose vertices represent letters. Then there's an edge between two vertices
    // for each word that starts with the start vertex's letter and ends with the end vertex's
    // letter. For example, cat => edge between c and t because if you reach a word ending in c,
    // you can ride the edge representing the word cat to any word starting with t, like
    // ...c [cat] t... There are fast algorithms for determing Euler path (use all edges once),
    // but not for determining Hamiltonian path (uses all vertices once), so this transformation
    // really helps. Intuitively I guess the transformation helps so much because it's not the
    // words that matter (which words as vertices approach doesn't realize), it's just their
    // starting and ending letters (which words as edges approach does realize).
    public static bool Solve(string[] words)
    {
        // For convenience, map the words' starting and ending letters to arbitrary IDs
        // between [0, the number of distinct starting and ending letters).
        var startAndEndingLetterIDs = words.Select(w => w[0])
                                      .Union(words.Select(w => w[w.Length - 1]))
                                      .Select((l, i) => new { letter = l, ID = i })
                                      .ToDictionary(p => p.letter, p => p.ID);
        var directedLetterGraph = new DirectedGraph(startAndEndingLetterIDs.Count);

        foreach (string word in words)
        {
            directedLetterGraph.AddEdge(
                startVertexID: startAndEndingLetterIDs[word[0]],
                endVertexID: startAndEndingLetterIDs[word[word.Length - 1]]);
        }

        /* According to Wikipedia: A directed graph has an Eulerian path if and only if at most one
        * vertex has (out-degree) − (in-degree) = 1, at most one vertex has (in-degree) − (out-degree) = 1,
        * every other vertex has equal in-degree and out-degree, and all of its vertices with nonzero
        * degree belong to a single connected component of the underlying undirected graph...
        *  And it's a path, not a cycle that we're looking for--don't need to return to start word. */

        if (directedLetterGraph.Vertices.Count(v => v.OutDegree - v.InDegree == 1) > 1 ||
            directedLetterGraph.Vertices.Count(v => v.InDegree - v.OutDegree == 1) > 1 ||
            directedLetterGraph.Vertices
            .Where(v => v.OutDegree - v.InDegree != 1)
            .Where(v => v.InDegree - v.OutDegree != 1)
            .Any(v => v.OutDegree != v.InDegree))
        {
            return(false);
        }

        var undirectedLetterGraph = new UndirectedGraph(startAndEndingLetterIDs.Count);

        foreach (string word in words)
        {
            undirectedLetterGraph.AddEdge(
                firstVertexID: startAndEndingLetterIDs[word[0]],
                secondVertexID: startAndEndingLetterIDs[word[word.Length - 1]]);
        }

        return(undirectedLetterGraph.IsConnected());
    }
Пример #19
0
        public IsHamiltonianGraphAlgorithm(UndirectedGraph <TVertex, UndirectedEdge <TVertex> > graph)
        {
            // Create new graph without parallel edges
            var newGraph = new UndirectedGraph <TVertex, UndirectedEdge <TVertex> >(false, graph.EdgeEqualityComparer);

            foreach (var vertex in graph.Vertices)
            {
                newGraph.AddVertex(vertex);
            }
            foreach (var edge in graph.Edges)
            {
                newGraph.AddEdge(edge);
            }
            //Remove loops
            EdgePredicate <TVertex, UndirectedEdge <TVertex> > isLoop = e => e.Source.Equals(e.Target);

            newGraph.RemoveEdgeIf(isLoop);
            this.graph = newGraph;
        }
        public void TestAddEdge(object v1, object v2, int weight)
        {
            List <object> cities = new List <object>()
            {
                "Seattle",
                "LA",
                "Denver"
            };
            //Set up the graph
            UndirectedGraph g = new UndirectedGraph(cities);

            //Add edge
            g.AddEdge(v1, v2, weight);
            //Assert success - that v1 is in the adjacency list of v2 and vice versa
            Dictionary <string, int> v1Neighbors = g.GetNeighbors(v1);
            Dictionary <string, int> v2Neighbors = g.GetNeighbors(v2);

            Assert.True(v1Neighbors.ContainsValue(weight) && v2Neighbors.ContainsValue(weight));
        }
Пример #21
0
        private UndirectedGraph <int, int> GetGraph(int noOfNodes, int maxNoOfEdges)
        {
            var startTime = DateTime.UtcNow;
            var graph     = new UndirectedGraph <int, int>();
            var e         = 0;

            for (int n = 1; n <= noOfNodes && e <= maxNoOfEdges; n++)
            {
                for (int i = n + 1; i <= noOfNodes && e <= maxNoOfEdges; i++, e++)
                {
                    graph.AddEdge(n, i, 1);
                }
            }


            var endTime = DateTime.UtcNow;

            System.Diagnostics.Trace.WriteLine(String.Format("Completed graph construction in {0}", endTime.Subtract(startTime).TotalMilliseconds));
            return(graph);
        }
Пример #22
0
        public void AddEdgeTest()
        {
            string[]        lines           = File.ReadAllLines("MSTTestGraph.txt");
            int             n               = int.Parse(lines[0].Split(' ')[0]);
            int             m               = int.Parse(lines[0].Split(' ')[1]);
            UndirectedGraph undirectedGraph = new UndirectedGraph(new MatrixRepresentation(n));

            for (int i = 0; i < m; i++)
            {
                string[] tokens = lines[i + 1].Split(' ');
                int      from   = int.Parse(tokens[0]);
                int      to     = int.Parse(tokens[1]);
                double   cost   = double.Parse(tokens[2]);
                undirectedGraph.AddEdge(new Edge(from, to, cost));
            }
            if (undirectedGraph.Edges != m)
            {
                Assert.Fail();
            }
        }
        public void ShouldAutomaticallyAddNodesWhenAddingEdges(string iedges, string iexpectedNodes)
        {
            //Arrange
            var edges =
                ParseEdges(iedges).OrderBy(x => x.SourceNode).ThenBy(x => x.DestinationNode).ThenBy(x => x.Weight);
            var sut = new UndirectedGraph<char, int>();
            var expectedNodes =
                iexpectedNodes.Split(nodeSeparator, StringSplitOptions.RemoveEmptyEntries)
                    .Select(char.Parse)
                    .OrderBy(x => x);

            //Act
            foreach (var edge in edges)
            {
                sut.AddEdge(edge.SourceNode, edge.DestinationNode, edge.Weight);
            }
            var actual = sut.GetNodes().OrderBy(x => x);

            //Assert
            Assert.AreEqual(expectedNodes, actual.Select(x => x));
        }
Пример #24
0
        public void Return_10_Given_Graph_With_2_Vertexex_And_1_Edge()
        {
            // Arrange
            var graph = new UndirectedGraph();

            var a = new Vertex("A");
            var b = new Vertex("B");

            graph.AddVertex(a);
            graph.AddVertex(b);

            graph.AddEdge(a, b, 10);

            // Act
            var actual1 = graph.FindMaxWeightedPath(a, b);
            var actual2 = graph.FindMaxWeightedPath(b, a);

            // Assert
            Assert.Equal(10, actual1);
            Assert.Equal(10, actual2);
        }
Пример #25
0
        private void InitGraph()
        {
            int gridWidth  = _hexes.GetLength(0);
            int gridHeight = _hexes.GetLength(1);

            for (int j = 0; j < gridHeight; j++)
            {
                for (int i = 0; i < gridWidth; i++)
                {
                    _mG.AddVertex(_hexes[i, j].GetHexaPos().GetName());
                }
            }

            List <HexaGridEdge> .Enumerator etE = _edgeList.GetEnumerator();
            while (etE.MoveNext())
            {
                QuickGraph.Edge <string> e = new Edge <string>(etE.Current.GetA().GetName(),
                                                               etE.Current.GetB().GetName());
                _mG.AddEdge(e);
            }
        }
Пример #26
0
        /// <summary>
        /// dfs and add vertexs to heap during search,
        /// heap root is the vertex with most neighbors
        /// </summary>
        /// <param name="n">N.</param>
        /// <param name="ihash"></param>
        /// <param name="set"></param>
        /// <param name="subGraph" />
        void DfsSearch(UndirectedGraph <IHash, Edge <IHash> > n, IHash ihash, HashSet <IHash> set, UndirectedGraph <IHash, Edge <IHash> > subGraph, BinaryHeap <int, IHash> binaryHeap)
        {
            set.Add(ihash);
            subGraph.AddVertex(ihash);
            binaryHeap.Add(n.AdjacentEdges(ihash).Count(), ihash);
            foreach (var edge in n.AdjacentEdges(ihash))
            {
                IHash nei = edge.Source == ihash ? edge.Target : edge.Source;

                //build subgraph
                subGraph.AddVertex(nei);
                subGraph.AddEdge(edge);

                if (set.Contains(nei))
                {
                    continue;
                }

                DfsSearch(n, nei, set, subGraph, binaryHeap);
            }
        }
Пример #27
0
        public void ShouldAutomaticallyAddNodesWhenAddingEdges(string iedges, string iexpectedNodes)
        {
            //Arrange
            var edges =
                ParseEdges(iedges).OrderBy(x => x.SourceNode).ThenBy(x => x.DestinationNode).ThenBy(x => x.Weight);
            var sut           = new UndirectedGraph <char, int>();
            var expectedNodes =
                iexpectedNodes.Split(nodeSeparator, StringSplitOptions.RemoveEmptyEntries)
                .Select(char.Parse)
                .OrderBy(x => x);

            //Act
            foreach (var edge in edges)
            {
                sut.AddEdge(edge.SourceNode, edge.DestinationNode, edge.Weight);
            }
            var actual = sut.GetNodes().OrderBy(x => x);

            //Assert
            Assert.AreEqual(expectedNodes, actual.Select(x => x));
        }
        private AbstractGraph <int, int> GetMockGraph(string igraph, int edgeWeight)
        {
            var edges = igraph.Split(_edgeSeparator, StringSplitOptions.RemoveEmptyEntries);
            var graph = new UndirectedGraph <int, int>();

            foreach (var edge in edges)
            {
                var nodesConnectingEdge =
                    edge.Split(_nodeSeparator, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                if (nodesConnectingEdge.Count == 1)
                {
                    graph.AddNode(nodesConnectingEdge.Single());
                }
                else
                {
                    graph.AddEdge(nodesConnectingEdge.First(), nodesConnectingEdge.Last(), edgeWeight);
                }
            }

            return(graph);
            //var mockGraph = MockRepository.GenerateStub<AbstractGraph<int, int>>();

            //var nodes = new List<int>();
            //foreach (var edge in edges)
            //{
            //    var nodesConnectingEdge = edge.Split(nodeSeparator).Select(int.Parse).ToList();
            //    if (nodes.Contains(nodesConnectingEdge.First()))
            //    {
            //        nodes.Add(nodesConnectingEdge.First());
            //    }
            //    if (nodes.Contains(nodesConnectingEdge.Last()))
            //    {
            //        nodes.Add(nodesConnectingEdge.Last());
            //    }
            //}
            //mockGraph.Stub(x => x.GetNodes()).Return(nodes);
            ////      mockGraph.Stub(x=>x.GetNeighbours(1)).IgnoreArguments().Do()
            //return mockGraph;
        }
Пример #29
0
    // Enumerate all undirected graphs on `vertices` number of vertices
    // Takes no account of symmetry so e.g. returns a lot of graphs with one edge (though these
    // are all isomorphic).
    static IEnumerable <UndirectedGraph <int> > AllUndirectedGraphs(int vertices)
    {
        var choices = Product(new List <int> {
            0, 1
        }, vertices * (vertices - 1) / 2);

        foreach (var choice in choices)
        {
            var graph = new UndirectedGraph <int>();
            for (int v = 0, index = 0; v < vertices; ++v)
            {
                for (int u = v + 1; u < vertices; ++u, ++index)
                {
                    if (choice[index] == 1)
                    {
                        graph.AddEdge(v, u);
                    }
                }
            }
            yield return(graph);
        }
    }
Пример #30
0
        public void Chordal()
        {
            var graph = new UndirectedGraph <char, EdgeData>();

            graph.AddNodes('a', 'b', 'c', 'd', 'e');
            graph.AddEdges(
                ('a', 'b', dummyEdgeData),
                ('a', 'c', dummyEdgeData),
                ('b', 'c', dummyEdgeData),
                ('b', 'd', dummyEdgeData),
                ('b', 'e', dummyEdgeData),
                ('c', 'd', dummyEdgeData),
                ('d', 'e', dummyEdgeData)
                );

            graph.Chordal.Should().BeTrue();

            graph.AddNode('f');
            graph.AddEdge('a', 'f', dummyEdgeData);

            graph.Chordal.Should().BeFalse();
        }
Пример #31
0
    private int TreeDiameter(int[][] edges)
    {
        UndirectedGraph       graph   = new UndirectedGraph();
        Dictionary <int, int> map     = new Dictionary <int, int>();
        HashSet <int>         visited = new HashSet <int>();

        for (int i = 0; i < edges.Length; i++)
        {
            graph.AddEdge(edges[i][0], edges[i][1]);
        }

        int max = 0;

        for (int i = 0; i < edges.Length; i++)
        {
            int count = 0;
            map[i] = Dfs(graph, i, visited, ref count);
            max    = Math.Max(max, map[i]);
        }

        return(max);
    }
Пример #32
0
        private static UndirectedGraph <int, Edge <int> > CreateFinalGraph(int numberOfPeople, List <Tuple <int, int> > pairs)
        {
            var finalGraph = new UndirectedGraph <int, Edge <int> >();

            for (int i = 0; i < pairs.Count; i++)
            {
                finalGraph.AddVertex(i);
            }

            for (int i = 0; i < pairs.Count; i++)
            {
                for (int j = 0; j < pairs.Count; j++)
                {
                    if (i != j && !HaveCommonVertex(pairs[i], pairs[j]))
                    {
                        finalGraph.AddEdge(new Edge <int>(i, j));
                    }
                }
            }

            return(finalGraph);
        }
Пример #33
0
        public ErdösRenyiModel(long numberOfNodes, double probability) : base(numberOfNodes)
        {
            _probability = probability;

            Graph = new UndirectedGraph <int, UndirectedEdge <int> >();

            _probability = probability;
            MaxEdges     = numberOfNodes * (numberOfNodes - 1) / 2;
            var edges = MaxEdges * probability;

            MaxEdges = (long)edges;
            // Console.WriteLine(edges);
            for (int i = 1; i <= NumberOfNodes; i++)
            {
                Graph.AddVertex(i);
            }

            if (probability.Equals(0.0))
            {
                return;
            }

            Random rand = new Random();

            for (int i = 1; i <= NumberOfNodes; i++)
            {
                for (int j = i + 1; j <= NumberOfNodes; j++)
                {
                    //if(i==j) continue;

                    if (probability.Equals(1.0) || rand.NextDouble() <= probability)
                    {
                        Graph.AddEdge(new UndirectedEdge <int>(i, j));
                        Count++;
                    }
                }
            }
        }
        private AbstractGraph<int, int> GetMockGraph(string igraph, int edgeWeight)
        {
            var edges = igraph.Split(_edgeSeparator, StringSplitOptions.RemoveEmptyEntries);
            var graph = new UndirectedGraph<int, int>();
            foreach (var edge in edges)
            {
                var nodesConnectingEdge =
                    edge.Split(_nodeSeparator, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                if (nodesConnectingEdge.Count == 1)
                {
                    graph.AddNode(nodesConnectingEdge.Single());
                }
                else
                {
                    graph.AddEdge(nodesConnectingEdge.First(), nodesConnectingEdge.Last(), edgeWeight);
                }
            }

            return graph;
            //var mockGraph = MockRepository.GenerateStub<AbstractGraph<int, int>>();

            //var nodes = new List<int>();
            //foreach (var edge in edges)
            //{
            //    var nodesConnectingEdge = edge.Split(nodeSeparator).Select(int.Parse).ToList();
            //    if (nodes.Contains(nodesConnectingEdge.First()))
            //    {
            //        nodes.Add(nodesConnectingEdge.First());
            //    }
            //    if (nodes.Contains(nodesConnectingEdge.Last()))
            //    {
            //        nodes.Add(nodesConnectingEdge.Last());
            //    }
            //}
            //mockGraph.Stub(x => x.GetNodes()).Return(nodes);
            ////      mockGraph.Stub(x=>x.GetNeighbours(1)).IgnoreArguments().Do()
            //return mockGraph;
        }
Пример #35
0
        public FormMain()
        {
            map        = LoadMap("BeijingSubwayMap.json");
            stationIds = new Dictionary <string, int>();
            lineIds    = new Dictionary <string, int>();
            graph      = new UndirectedGraph();

            for (int i = 0; i < map.Stations.Count; i++)
            {
                stationIds[map.Stations[i].Name] = i;
            }

            for (int i = 0; i < map.Lines.Count; i++)
            {
                lineIds[map.Lines[i].Name] = i;
            }

            foreach (SubwayLine line in map.Lines)
            {
                for (int i = 1; i < line.Path.Count; i++)
                {
                    int from = stationIds[line.Path[i - 1]];
                    int to   = stationIds[line.Path[i]];
                    graph.AddEdge(from, to, lineIds[line.Name]);
                }
            }

            path = new List <Point>();

            InitializeComponent();
            this.BackgroundImageLayout = ImageLayout.Zoom;

            this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
            this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);

            this.pictureBox1.MouseUp    += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
            this.pictureBox1.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseWheel);
        }
Пример #36
0
        private UndirectedGraph <Guid, Edge <Guid> > GetGraphForTracing()
        {
            if (_g != null)
            {
                return(_g);
            }

            _g = new UndirectedGraph <Guid, Edge <Guid> >();

            foreach (var node in Nodes)
            {
                _g.AddVertex(node.Key);
            }

            foreach (var link in Edges)
            {
                var edge = new Edge <Guid>(link.Value.StartNode.Id, link.Value.EndNode.Id);
                _g.AddEdge(edge);
                _edgeToLinkId.Add(edge, link.Key);
            }

            return(_g);
        }
        public void ShouldAddEdgeGivenSourceDestinationNodeAndEdgeWeight(string iedges, char isourceNode,
            string iexpectedNeighbourNodes)
        {
            //Arrange
            var expectedNeighbourNodes =
                iexpectedNeighbourNodes.Split(nodeSeparator, StringSplitOptions.RemoveEmptyEntries)
                    .Select(char.Parse)
                    .OrderBy(x => x);
            var edges =
                ParseEdges(iedges).OrderBy(x => x.SourceNode).ThenBy(x => x.DestinationNode).ThenBy(x => x.Weight);
            var sut = new UndirectedGraph<char, int>();

            //Act
            foreach (var edge in edges)
            {
                sut.AddEdge(edge.SourceNode, edge.DestinationNode, edge.Weight);
            }

            var actual = sut.GetNeighbours(isourceNode).OrderBy(x => x);

            //Assert
            Assert.AreEqual(expectedNeighbourNodes, actual);
        }
Пример #38
0
        public void ShouldAddEdgeGivenSourceDestinationNodeAndEdgeWeight(string iedges, char isourceNode,
                                                                         string iexpectedNeighbourNodes)
        {
            //Arrange
            var expectedNeighbourNodes =
                iexpectedNeighbourNodes.Split(nodeSeparator, StringSplitOptions.RemoveEmptyEntries)
                .Select(char.Parse)
                .OrderBy(x => x);
            var edges =
                ParseEdges(iedges).OrderBy(x => x.SourceNode).ThenBy(x => x.DestinationNode).ThenBy(x => x.Weight);
            var sut = new UndirectedGraph <char, int>();

            //Act
            foreach (var edge in edges)
            {
                sut.AddEdge(edge.SourceNode, edge.DestinationNode, edge.Weight);
            }

            var actual = sut.GetNeighbours(isourceNode).OrderBy(x => x);

            //Assert
            Assert.AreEqual(expectedNeighbourNodes, actual);
        }
Пример #39
0
        public void SolveTest()
        {
            string[]        lines    = File.ReadAllLines("CCTestGraph.txt");
            int             n        = int.Parse(lines[0].Split(' ')[0]);
            int             m        = int.Parse(lines[0].Split(' ')[1]);
            int             conCount = int.Parse(lines[lines.Length - 1]);
            UndirectedGraph graph    = new UndirectedGraph(new MatrixRepresentation(n));

            for (int i = 0; i < m; i++)
            {
                string[] tokens = lines[i + 1].Split(' ');
                int      from   = int.Parse(tokens[0]);
                int      to     = int.Parse(tokens[1]);
                graph.AddEdge(new Edge(from, to, 1));
            }
            graph.ConnectedComponentsSolver = new DepthFirstSearchCC();
            var components = graph.GetConnectedComponents();

            if (components.Count != conCount)
            {
                Assert.Fail();
            }
        }
        private UndirectedGraph <string, TaggedEdge <string, double> > GetUndirectedFullGraph(int vert)
        {
            Console.WriteLine("Start");
            var usedEdge  = new List <KeyValuePair <int, int> >();
            var random    = new Random();
            var graph     = new UndirectedGraph <string, TaggedEdge <string, double> >();
            var trueGraph = new UndirectedGraph <string, TaggedEdge <string, double> >();
            var ds        = new ForestDisjointSet <string>(vert);

            for (int i = 0; i < vert; i++)
            {
                graph.AddVertex(i.ToString());
                trueGraph.AddVertex(i.ToString());
                ds.MakeSet(i.ToString());
            }
            for (int i = 0; i < vert; i++)
            {
                for (int j = i + 1; j < vert; j++)
                {
                    graph.AddEdge(new TaggedEdge <string, double>(i.ToString(), j.ToString(), random.Next(100)));
                }
            }
            return(graph);
        }
Пример #41
0
        public static UndirectedGraph <int, Edge <int> > CreateGraphArrayOfNodesAndEdges([PexAssumeNotNull] int[] nodes,
                                                                                         [PexAssumeNotNull] bool[] edges)
        {
            PexAssume.IsTrue(edges.Length <= nodes.Length);
            PexAssume.AreDistinctValues(nodes);
            PexAssume.TrueForAll(nodes, e => e != 0);

            UndirectedGraph <int, Edge <int> > g = new UndirectedGraph <int, Edge <int> >(false);

            foreach (int ele in nodes)
            {
                g.AddVertex(ele);
            }

            for (int i = 0; i < edges.Length; i++)
            {
                int source = PexChoose.IndexValue("indexed value", nodes);
                if (edges[i] == false)
                {
                    g.AddEdge(new Edge <int>(nodes[source], nodes[i]));
                }
            }
            return(g);
        }
Пример #42
0
        public void SolveTest()
        {
            string[]        lines           = File.ReadAllLines("MSTTestGraph.txt");
            int             n               = int.Parse(lines[0].Split(' ')[0]);
            int             m               = int.Parse(lines[0].Split(' ')[1]);
            int             mstCost         = int.Parse(lines[lines.Length - 1]);
            UndirectedGraph undirectedGraph = new UndirectedGraph(new WeightedMatrixRepresentation(n));

            for (int i = 0; i < m; i++)
            {
                string[] tokens = lines[i + 1].Split(' ');
                int      from   = int.Parse(tokens[0]);
                int      to     = int.Parse(tokens[1]);
                double   cost   = double.Parse(tokens[2]);
                undirectedGraph.AddEdge(new Edge(from, to, cost));
            }
            PrimMST primMST = new PrimMST();

            undirectedGraph.MSTSolver = primMST;
            var mst = undirectedGraph.GetMinimumSpanningTree();

            if (mst.Count != n - 1)
            {
                Assert.Fail();
            }
            int totalCost = 0;

            foreach (Edge baseEdge in mst)
            {
                totalCost += (int)baseEdge.Cost;
            }
            if (totalCost != mstCost)
            {
                Assert.Fail();
            }
        }
Пример #43
0
        private static void AddNewEdge(Pixel p1, Pixel p2, Color cA, Color cB, UndirectedGraph<Pixel, TaggedUndirectedEdge<Pixel, EdgeTag>> graph)
        {
            TaggedUndirectedEdge<Pixel, EdgeTag> e;
            TaggedUndirectedEdge<Pixel, EdgeTag> e1;
            TaggedUndirectedEdge<Pixel, EdgeTag> e2;
            bool b = !cA.Equals(cB);

            graph.TryGetEdge(p1, p2, out e1);
            graph.TryGetEdge(p2, p1, out e2);
            p1.color = cA;
            p1.colorB = cB;
            p2.color = cA;
            p2.colorB = cB;

            if (e1 == null && e2 == null && b) // adicionado o "b" para adicionar apenas arestas visiveis ao grafo
            {
                e = new TaggedUndirectedEdge<Pixel, EdgeTag>(p1, p2, new EdgeTag(cA, cB, b));
                graph.AddEdge(e);
                if (b) //conta valencia apenas se for visivel
                {
                    p1.valence++;
                    p2.valence++;
                }
            }
        }
Пример #44
0
        public static UndirectedGraph CreateUndirectedGraph36()
        {
            var g = new UndirectedGraph(12);

            #region add path

            //first component
            g.AddEdge(0, 1);
            g.AddEdge(0, 4);

            g.AddEdge(4, 8);
            g.AddEdge(4, 9);

            g.AddEdge(8, 9);

            //second component
            //node F is alone

            //third component
            g.AddEdge(2, 3);
            g.AddEdge(2, 6);
            g.AddEdge(2, 7);

            g.AddEdge(3, 7);

            g.AddEdge(6, 7);
            g.AddEdge(6, 10);

            g.AddEdge(7, 10);
            g.AddEdge(7, 11);

            #endregion

            return g;
        }
Пример #45
0
        public void InitializeGraph(String goPath)
        {
            AdjacencyGraph<Int32, Edge<Int32>> graph = null;
            String line, goNamespace = null;
            Int32 currentTerm = 0;
            Int32 parentTerm = 0;

            using(StreamReader reader = new StreamReader(goPath)) {
                while (!reader.EndOfStream) {
                    line = reader.ReadLine();
                    if (line.StartsWith("[Typedef]")) {
                        reader.ReadToEnd();
                    } else if (line.StartsWith("id:")) {
                        currentTerm  = Int32.Parse(line.Substring(7,7));
                    } else if (line.StartsWith("namespace:")) {
                        goNamespace = line.Substring(11);
                    } else if (line.StartsWith("is_a:")) {
                        if (!graphs.ContainsKey(goNamespace)) {
                            graphs.Add(goNamespace, new AdjacencyGraph<Int32, Edge<Int32>>());
                        }

                        graph = graphs[goNamespace];
                        graph.AddVertex(currentTerm);
                        parentTerm = Int32.Parse(line.Substring(10,7));
                        graph.AddVertex(parentTerm);
                        graph.AddEdge(new Edge<Int32>(currentTerm,parentTerm));
                    }
                }
            }

            foreach(String ns in graphs.Keys) {
                var g = graphs[ns];
                var newGraph = new UndirectedGraph<Int32, UndirectedEdge<Int32>>();
                foreach (Edge<Int32> e in g.Edges) {
                    newGraph.AddVertex(e.Source);
                    newGraph.AddVertex(e.Target);
                    newGraph.AddEdge(new UndirectedEdge<Int32>(e.Source, e.Target));
                }
                undirectedGraphs.Add(ns, newGraph);
            }
        }
        public void Initialize()
        {
            _graph =  new UndirectedGraph<string, string>();
            _vertex1 = _graph.CreateVertex("Penis");
            _vertex2 = _graph.CreateVertex("Tomato");
            _vertex3 = _graph.CreateVertex("Isa");
            _vertex4 = _graph.CreateVertex("Robin");
            _vertex5 = _graph.CreateVertex("Außenseiter");

            _edge1 = _graph.AddEdge(_vertex1, _vertex2);
            _edge2 = _graph.AddEdge(_vertex2, _vertex3);
            _edge3 = _graph.AddEdge(_vertex3, _vertex4);
            _edge4 = _graph.AddEdge(_vertex1, _vertex4);
        }
        public void InitializePathfindingGraph()
        {
            _graph = new UndirectedGraph<string, string>();

            _vertex1 = _graph.CreateVertex("A");
            _vertex2 = _graph.CreateVertex("B");
            _vertex3 = _graph.CreateVertex("C");
            _vertex4 = _graph.CreateVertex("D");
            _vertex5 = _graph.CreateVertex("E");
            _vertex6 = _graph.CreateVertex("F");
            _vertex7 = _graph.CreateVertex("G");
            _vertex8 = _graph.CreateVertex("H");
            _vertex9 = _graph.CreateVertex("K");

            _edge1 = _graph.AddEdge(_vertex1, _vertex2, 10, "AB");
            _edge2 = _graph.AddEdge(_vertex2, _vertex3, 10, "BC");
            _edge3 = _graph.AddEdge(_vertex1, _vertex4, 10, "AD");
            _edge4 = _graph.AddEdge(_vertex1, _vertex5, 15, "AE");
            _edge5 = _graph.AddEdge(_vertex4, _vertex5, 10, "DE");
            _edge6 = _graph.AddEdge(_vertex4, _vertex8, 15, "DH");
            _edge7 = _graph.AddEdge(_vertex2, _vertex5, 10, "BE");
            _edge8 = _graph.AddEdge(_vertex5, _vertex6, 10, "EF");
            _edge9 = _graph.AddEdge(_vertex5, _vertex8, 10, "EH");
            _edge10 = _graph.AddEdge(_vertex5, _vertex3, 15, "EC");
            _edge11 = _graph.AddEdge(_vertex5, _vertex9, 15, "EK");
            _edge12 = _graph.AddEdge(_vertex3, _vertex6, 10, "CF");
            _edge13 = _graph.AddEdge(_vertex3, _vertex7, 50, "CG");
            _edge14 = _graph.AddEdge(_vertex8, _vertex9, 10, "HK");
            _edge15 = _graph.AddEdge(_vertex9, _vertex6, 10, "KF");
            _edge16 = _graph.AddEdge(_vertex9, _vertex7, 20, "KG");
        }
Пример #48
0
        public static UndirectedGraph CreateUndirectedGraph32()
        {
            var g = new UndirectedGraph(10);

            #region add path

            g.AddEdge(0, 1);
            g.AddEdge(0, 2);
            g.AddEdge(0, 3);

            g.AddEdge(1, 4);
            g.AddEdge(1, 5);

            g.AddEdge(2, 5);

            g.AddEdge(3, 6);
            g.AddEdge(3, 7);

            g.AddEdge(4, 8);
            g.AddEdge(4, 9);

            g.AddEdge(6, 7);

            g.AddEdge(8, 9);

            #endregion

            return g;
        }
Пример #49
0
        public static void createTables()
        {
            // Create graph
            var graph = new UndirectedGraph<int, Edge<int>>();

            // Add vertices to the graph
            for (var i = 0; i < FormMain.nodes.Count; i++)
                graph.AddVertex(i);

            // Create edges
            var edgeCost = new Dictionary<Edge<int>, double>();
            for (var i = 0; i < FormMain.edges.Count; i++)
            {
                var quickGraphEdge = new Edge<int>(FormMain.nodes.IndexOf(FormMain.edges[i].nodes[0]), FormMain.nodes.IndexOf(FormMain.edges[i].nodes[1]));
                graph.AddEdge(quickGraphEdge);
                edgeCost.Add(quickGraphEdge, FormMain.edges[i].Weight);
            }

            // Initialize tables
            distanceTable = new double[FormMain.nodes.Count, FormMain.nodes.Count];
            pathTable = new List<int>[FormMain.nodes.Count, FormMain.nodes.Count];
            for (var i = 0; i < FormMain.nodes.Count; i++)
                for (var j = 0; j < FormMain.nodes.Count; j++)
                {
                    distanceTable[i, j] = double.PositiveInfinity;
                    pathTable[i, j] = new List<int>();
                }

            // Create tables
            for (var source = 0; source < FormMain.nodes.Count; source++)
            {
                // We want to use Dijkstra on this graph
                var dijkstra = new UndirectedDijkstraShortestPathAlgorithm<int, Edge<int>>(graph, edge => edgeCost[edge]);

                // attach a distance observer to give us the shortest path distances
                var distObserver = new UndirectedVertexDistanceRecorderObserver<int, Edge<int>>(edge => edgeCost[edge]);
                distObserver.Attach(dijkstra);

                // Attach a Vertex Predecessor Recorder Observer to give us the paths
                var predecessorObserver = new UndirectedVertexPredecessorRecorderObserver<int, Edge<int>>();
                predecessorObserver.Attach(dijkstra);

                // Run the algorithm for current Node
                dijkstra.Compute(source);

                // Add values to table
                foreach (var target in distObserver.Distances)
                {
                    distanceTable[source, target.Key] = target.Value;
                    IEnumerable<Edge<int>> path;
                    if (predecessorObserver.TryGetPath(target.Key, out path))
                        pathTable[source, target.Key].AddRange(path.Select(edge => edge.Source).Concat(path.Select(edge => edge.Target)).Distinct().OrderBy(next => distObserver.Distances[next]));
                }
            }

            // Create route tables
            foreach (var source in FormMain.nodes)
                source.routeTable = FormMain.nodes.ToDictionary(target => target, target =>
                    (
                        from edge in FormMain.edges
                        where edge.nodes.Contains(source)
                        let adjacent = edge.nodes[0] != source ? edge.nodes[0] : edge.nodes[1]
                        where !pathTable[adjacent.ID, target.ID].Contains(source.ID)
                        orderby edge.Weight + distanceTable[adjacent.ID, target.ID] ascending
                        select adjacent
                    ).ToList());

            TablesRequired = false;
        }
        public void InitializeTwoGraphGraph()
        {
            _graph = new UndirectedGraph<string, string>();
            _vertex1 = _graph.CreateVertex("A");
            _vertex2 = _graph.CreateVertex("B");
            _vertex3 = _graph.CreateVertex("C");
            _vertex4 = _graph.CreateVertex("D");
            _vertex5 = _graph.CreateVertex("E");

            _edge1 = _graph.AddEdge(_vertex1, _vertex2);
            _edge3 = _graph.AddEdge(_vertex3, _vertex4);
            _edge4 = _graph.AddEdge(_vertex4, _vertex5);
            _edge5 = _graph.AddEdge(_vertex5, _vertex3);
        }
Пример #51
0
        public static UndirectedGraph CreateUndirectedGraph41()
        {
            var g = new UndirectedGraph(6);

            g.AddEdge('A', 'B');
            g.AddEdge('A', 'S');
            g.AddEdge('B', 'C');
            g.AddEdge('C', 'S');
            g.AddEdge('D', 'E');
            g.AddEdge('D', 'S');
            g.AddEdge('E', 'S');

            return g;
        }