Ejemplo n.º 1
0
        public void IsBipartite_ForBiggerGraphs()
        {
            // This graph is some bipartite mess. Odds and evens go in their own set, edges between them haphazardly.
            var graph = SimpleGraph.CreateFromOneBasedEdges(22, new[, ]
            {
                { 2, 3 }, { 2, 9 }, { 2, 11 }, { 2, 15 },
                { 4, 1 }, { 4, 7 }, { 4, 11 }, { 4, 17 },
                { 6, 1 }, { 6, 11 }, { 6, 7 }, { 6, 15 },
                { 8, 1 }, { 8, 15 }, { 8, 13 }, { 8, 17 },
                { 10, 1 }, { 10, 3 }, { 10, 13 }, { 10, 15 },
                { 14, 1 }, { 16, 3 }, { 16, 7 }, { 16, 17 },
                { 16, 1 }, { 16, 3 }, { 16, 7 }, { 16, 17 },
                { 16, 9 }, { 16, 11 }, { 16, 5 }, { 16, 19 },
                { 18, 9 }, { 18, 11 }, { 18, 5 }, { 18, 19 },
                { 20, 21 }
            });

            Assert.IsTrue(graph.IsBipartite());

            // This graph is like above, except I threw in an edge between an even pair of vertices.
            graph = SimpleGraph.CreateFromOneBasedEdges(22, new[, ]
            {
                { 2, 3 }, { 2, 9 }, { 2, 11 }, { 2, 15 },
                { 4, 1 }, { 4, 7 }, { 4, 11 }, { 4, 17 },
                { 6, 1 }, { 6, 11 }, { 6, 7 }, { 6, 15 },
                { 8, 1 }, { 8, 15 }, { 8, 13 }, { 8, 17 },
                { 10, 1 }, { 10, 3 }, { 10, 13 }, { 10, 15 },
                { 14, 1 }, { 16, 3 }, { 16, 7 }, { 16, 17 },
                { 16, 1 }, { 16, 3 }, { 16, 7 }, { 16, 17 },
                { 16, 9 }, { 16, 11 }, { 16, 5 }, { 16, 19 },
                { 18, 9 }, { 18, 11 }, { 18, 5 }, { 18, 19 },
                { 20, 21 }, { 10, 16 }
            });
            Assert.IsFalse(graph.IsBipartite());
        }
        //Iterative depth-first search that returns the node with the target data.
        public static GraphNode <T> DFS <T>(this SimpleGraph <T> graph, T target)
        {
            if (graph == null || graph.Nodes.Count == 0)
            {
                return(null);
            }

            var visited = new HashSet <GraphNode <T> >();
            var stack   = new DataStructures.Stack <GraphNode <T> >();

            stack.Push(graph.Root);

            while (!stack.IsEmpty)
            {
                GraphNode <T> curr = stack.Pop();

                if (visited.Contains(curr))
                {
                    continue;
                }

                if (curr.Data.Equals(target))
                {
                    return(curr);
                }

                visited.Add(curr);
                foreach (GraphNode <T> neighbor in curr.Neighbors)
                {
                    stack.Push(neighbor);
                }
            }

            return(null);
        }
Ejemplo n.º 3
0
        public void FindFurthestVertex3()
        {
            // This graph is a line broken in two.
            var graph = SimpleGraph.CreateFromZeroBasedEdges(6, new[, ]
            {
                { 0, 1 }, { 1, 2 }, { 3, 4 }, { 4, 5 }
            });

            Assert.AreEqual(2, graph.FindFurthestVertex(0).Item1.ID);
            Assert.AreEqual(2, graph.FindFurthestVertex(0).Item2);

            Assert.IsTrue(graph.FindFurthestVertex(1).Item1.ID == 2 ||
                          graph.FindFurthestVertex(1).Item1.ID == 0);
            Assert.AreEqual(1, graph.FindFurthestVertex(1).Item2);

            Assert.AreEqual(0, graph.FindFurthestVertex(2).Item1.ID);
            Assert.AreEqual(2, graph.FindFurthestVertex(2).Item2);

            Assert.AreEqual(5, graph.FindFurthestVertex(3).Item1.ID);
            Assert.AreEqual(2, graph.FindFurthestVertex(3).Item2);

            Assert.IsTrue(graph.FindFurthestVertex(4).Item1.ID == 3 ||
                          graph.FindFurthestVertex(4).Item1.ID == 5);
            Assert.AreEqual(1, graph.FindFurthestVertex(4).Item2);

            Assert.AreEqual(3, graph.FindFurthestVertex(5).Item1.ID);
            Assert.AreEqual(2, graph.FindFurthestVertex(5).Item2);
        }
Ejemplo n.º 4
0
    static void Init()
    {
        // Get existing open window or if none, make a new one:
        SimpleGraph window = (SimpleGraph)EditorWindow.GetWindow(typeof(SimpleGraph));

        window.Show();
    }
        protected override void AssertPipGraphContent(PipGraph pipGraph, SimpleGraph file2file, StringTable stringTable)
        {
            AssertPipGraphCounts(pipGraph, new Dictionary <PipType, int>
            {
                [PipType.Process]       = file2file.NodeCount,
                [PipType.SealDirectory] = file2file.NodeCount,
            });
            var processPips = pipGraph.RetrievePipsOfType(PipType.Process).ToList();

            // assert edges exist
            Assert.All(
                file2file.Edges,
                edge =>
            {
                var errPrefix = $"Edge ({edge.Src})->({edge.Dest}) not found: ";
                var srcPip    = FindPipByTag(processPips, GetProcTag(edge.Src), stringTable);
                var destPip   = FindPipByTag(processPips, GetProcTag(edge.Dest), stringTable);
                var producedSealDirectoryPips = pipGraph.RetrievePipImmediateDependents(destPip).Where(pip => pip.PipType == PipType.SealDirectory).ToList();
                XAssert.AreEqual(1, producedSealDirectoryPips.Count, $"{errPrefix} expected to find exactly one SealDirectory dependency of Process Pip {destPip}");
                var producedSealDirectoryPip = producedSealDirectoryPips.First();
                var deps = pipGraph.RetrievePipImmediateDependents(producedSealDirectoryPip);
                if (!deps.Contains(srcPip))
                {
                    XAssert.Fail($"{errPrefix} expected edges between {srcPip} <-- {producedSealDirectoryPip} <-- {destPip}; dependencies of Pip {producedSealDirectoryPip} are: {XAssert.SetToString(deps)}");
                }
            });
        }
Ejemplo n.º 6
0
        public void FindFurthestVertex2()
        {
            // This graph is a line.
            var graph = SimpleGraph.CreateFromZeroBasedEdges(6, new[, ]
            {
                { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }
            });

            Assert.AreEqual(5, graph.FindFurthestVertex(0).Item1.ID);
            Assert.AreEqual(5, graph.FindFurthestVertex(0).Item2);

            Assert.AreEqual(5, graph.FindFurthestVertex(1).Item1.ID);
            Assert.AreEqual(4, graph.FindFurthestVertex(1).Item2);

            Assert.AreEqual(5, graph.FindFurthestVertex(2).Item1.ID);
            Assert.AreEqual(3, graph.FindFurthestVertex(2).Item2);

            Assert.AreEqual(0, graph.FindFurthestVertex(3).Item1.ID);
            Assert.AreEqual(3, graph.FindFurthestVertex(3).Item2);

            Assert.AreEqual(0, graph.FindFurthestVertex(4).Item1.ID);
            Assert.AreEqual(4, graph.FindFurthestVertex(4).Item2);

            Assert.AreEqual(0, graph.FindFurthestVertex(5).Item1.ID);
            Assert.AreEqual(5, graph.FindFurthestVertex(5).Item2);
        }
Ejemplo n.º 7
0
    private IEnumerator LinkSpheres()
    {
        Debug.Log("Linking Spheres");

        SphereGraph = new SimpleGraph(Spheres.Count, 2 * Portals.Count);

        // How much is our offset for the second arc
        int BidirectionOffset = Portals.Count;

        // Every portal is a connection between spheres, so lets do that
        foreach (CameraGraphPortalNode portal in Portals)
        {
            // Indices for the sphere nodes
            int SphereAIndex = Spheres.IndexOf(portal.A);
            int SphereBIndex = Spheres.IndexOf(portal.B);

            // Index for the portal
            int PortalIndex = Portals.IndexOf(portal);
            // Links are all bidirectional
            SphereGraph.SetNodeArc(SphereAIndex, PortalIndex, SphereBIndex);
            SphereGraph.SetNodeArc(SphereBIndex, PortalIndex + BidirectionOffset, SphereAIndex);

            // Gotta show off that cool debugging
            Debug.DrawLine(portal.A.transform.position, portal.B.transform.position, Color.red, 1.0f);

            if (ShouldOperationYield())
            {
                yield return(new WaitForEndOfFrame());
            }
        }

        Debug.Log("Linked " + SphereGraph.numNodes + " spheres with " + SphereGraph.numArcs + " arcs");
        yield return(null);
    }
Ejemplo n.º 8
0
 public void RegularGraphTest(SimpleGraph graph, int diameter)
 {
     for (int h = 1; h <= diameter; h++)
     {
         SimpleVertexSignature sig0 =
             new SimpleVertexSignature(0, h, graph);
         string zeroCanonical = sig0.ToCanonicalString();
         Console.Out.WriteLine(h + "\t" + zeroCanonical);
         for (int i = 1; i < graph.GetVertexCount(); i++)
         {
             SimpleVertexSignature sig =
                 new SimpleVertexSignature(i, h, graph);
             //                Assert.AreEqual(zeroCanonical, sig.ToCanonicalString());
             string canString = sig.ToCanonicalString();
             if (zeroCanonical.Equals(canString))
             {
                 //                    Console.Out.WriteLine("EQU");
             }
             else
             {
                 Console.Out.WriteLine("NEQ "
                                       + h + "\t" + i + "\t"
                                       + zeroCanonical + " " + canString);
             }
             Assert.AreEqual(zeroCanonical, canString);
         }
     }
 }
Ejemplo n.º 9
0
        public void BreadthFirstSearch_5_Vertex_Where_path_has_2v()
        {
            int size = 5;
            SimpleGraph <int> testGraph = new SimpleGraph <int>(size);

            testGraph.AddVertex(0); // добавляем вершины
            testGraph.AddVertex(10);
            testGraph.AddVertex(20);
            testGraph.AddVertex(30);
            testGraph.AddVertex(40);

            testGraph.AddEdge(0, 1); // добавление рёбер между вершинами
            testGraph.AddEdge(0, 3);
            testGraph.AddEdge(0, 4);

            testGraph.AddEdge(1, 2);
            testGraph.AddEdge(2, 3);
            testGraph.AddEdge(3, 4);

            List <Vertex <int> > vList = testGraph.BreadthFirstSearch(0, 4); // попытка построения пути из 0 (0) в 4 (40).

            vList.ForEach((item) => Console.Write(" {0}", item.Value));

            Assert.IsNotNull(vList);
            Assert.IsTrue(vList.Count == 2);
        }
Ejemplo n.º 10
0
        private static bool HasPath(object adjacentRingA, object adjacentRingB, SimpleGraph <object> graph)
        {
            HashSet <object> visited    = new HashSet <object>();
            bool             more       = true;
            List <object>    actives    = new List <object>();
            List <object>    newActives = new List <object>();

            actives.Add(adjacentRingB);
            while (more)
            {
                more = false;
                foreach (object cur in actives)
                {
                    visited.Add(cur);
                    object[] items = graph.GetAdjacent(cur);
                    foreach (object o in items)
                    {
                        if (object.ReferenceEquals(o, adjacentRingA))
                        {
                            return(true);
                        }
                        if (visited.Add(o))
                        {
                            more = true;
                            newActives.Add(o);
                        }
                    }
                }
                actives = newActives;
                newActives.Clear();
            }
            return(false);
        }
Ejemplo n.º 11
0
        public void AddEdge_in_5v_Graph_If_v1_Is_not_Exists()
        {
            int size = 5;
            SimpleGraph <int> testGraph = new SimpleGraph <int>(size);

            testGraph.AddVertex(19);
            testGraph.AddVertex(18);
            testGraph.AddVertex(17);
            testGraph.AddVertex(16);

            testGraph.AddEdge(0, 4);

            for (int i = 0; i < testGraph.m_adjacency.GetLength(0); i++)
            {
                for (int j = 0; j < testGraph.m_adjacency.GetLength(1); j++)
                {
                    Console.Write(testGraph.m_adjacency[i, j] + " ");
                }
                Console.WriteLine();
            }
            Assert.IsTrue(testGraph.vertex[0].Value == 19); // вершина не изменились
            Assert.IsTrue(testGraph.vertex[1].Value == 18);
            Assert.IsTrue(testGraph.vertex[2].Value == 17);
            Assert.IsTrue(testGraph.vertex[3].Value == 16);
            Assert.IsNull(testGraph.vertex[4]);              // вершина не существует
            Assert.AreEqual(0, testGraph.m_adjacency[0, 4]); // ребро не добавлено к v0
            Assert.AreEqual(0, testGraph.m_adjacency[4, 0]); // ребро не добавлено к v4
        }
Ejemplo n.º 12
0
        public void AddVertex_5v_in_5v_Graph()
        {
            int size = 5;
            SimpleGraph <int> testGraph = new SimpleGraph <int>(size);

            testGraph.AddVertex(19);
            testGraph.AddVertex(18);
            testGraph.AddVertex(17);
            testGraph.AddVertex(16);
            testGraph.AddVertex(15);

            Assert.IsTrue(testGraph.vertex[0].Value == 19);
            Assert.IsTrue(testGraph.vertex[1].Value == 18);
            Assert.IsTrue(testGraph.vertex[2].Value == 17);
            Assert.IsTrue(testGraph.vertex[3].Value == 16);
            Assert.IsTrue(testGraph.vertex[4].Value == 15);
            Assert.AreEqual(size, testGraph.max_vertex);
            Assert.AreEqual(size, testGraph.vertex.Length);
            Assert.AreEqual(size, testGraph.m_adjacency.GetLength(0));
            Assert.AreEqual(size, testGraph.m_adjacency.GetLength(1));
            Assert.AreEqual(0, testGraph.m_adjacency[0, 0]);
            Assert.AreEqual(0, testGraph.m_adjacency[1, 0]);
            Assert.AreEqual(0, testGraph.m_adjacency[2, 0]);
            Assert.AreEqual(0, testGraph.m_adjacency[3, 0]);
            Assert.AreEqual(0, testGraph.m_adjacency[4, 0]);
        }
Ejemplo n.º 13
0
        public void AddVertex_1v_in_5v_Graph()
        {
            int size = 5;
            SimpleGraph <int> testGraph = new SimpleGraph <int>(5);

            testGraph.AddVertex(19);

            foreach (Vertex <int> item in testGraph.vertex)
            {
                if (item != null)
                {
                    Console.Write(item.Value + ", ");
                }
                else
                {
                    Console.Write("null, ");
                }
            }

            Assert.IsTrue(testGraph.vertex[0].Value == 19);
            Assert.AreEqual(size, testGraph.max_vertex);
            Assert.AreEqual(size, testGraph.vertex.Length);
            Assert.AreEqual(size, testGraph.m_adjacency.GetLength(0));
            Assert.AreEqual(size, testGraph.m_adjacency.GetLength(1));
            Assert.AreEqual(0, testGraph.m_adjacency[0, 0]);
        }
Ejemplo n.º 14
0
        public void WeakVertices_in_3v_where_Graph_Is_Triangle()
        {
            int size = 3;
            SimpleGraph <int> testGraph = new SimpleGraph <int>(size);

            testGraph.AddVertex(0); // добавляем вершины
            testGraph.AddVertex(10);
            testGraph.AddVertex(20);

            testGraph.AddEdge(0, 1); // добавление рёбер между вершинами
            testGraph.AddEdge(0, 2);
            testGraph.AddEdge(1, 2);

            List <Vertex <int> > WeakList = testGraph.WeakVertices();

            int expectedCount = 0;
            int actualCount   = WeakList.Count;

            if (WeakList.Count != 0)
            {
                WeakList.ForEach((item) => Console.Write("{0} ", item.Value));
            }
            else
            {
                Console.WriteLine("[]");
            }

            Assert.IsNotNull(WeakList);
            Assert.AreEqual(expectedCount, actualCount);
        }
Ejemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="start"></param>
        private static void breadthFirstSearch(SimpleGraph graph, char start)
        {
            // 初始化队列
            Queue queue = new Queue();

            queue.Enqueue(start);//插入数据
            Dictionary <char, bool> visited = new Dictionary <char, bool>();

            visited[start] = true;//给字典对于键值对赋值

            while (queue.Count != 0)
            {
                char current = (char)queue.Dequeue();//移除并返回队首元素
                Console.WriteLine("队首元素: " + current);

                foreach (char next in graph.neighbors(current))
                {
                    //当next 不在visited中时
                    if (!visited.ContainsKey(next))
                    {
                        queue.Enqueue(next);
                        visited[next] = true;
                    }
                }
            }
        }
Ejemplo n.º 16
0
    static NAKANJ()
    {
        _knightMoveGraph = new SimpleGraph(vertexCount: 64);

        // The problem's chessboard has rows from 8 to 1 and columns from a to h,
        // starting in the upper left corner. This one will have rows from 0 to 7
        // and columns from 0 to 7, starting in the upper left hand corner.
        for (int r = 0; r < 8; ++r)
        {
            for (int c = 0; c < 8; ++c)
            {
                int thisVertexID = GetVertexID(r, c);

                foreach (var knightMoveTransformation in _knightMoveTransformations)
                {
                    int rowTransformation    = knightMoveTransformation.Item1;
                    int columnTransformation = knightMoveTransformation.Item2;

                    int movedToVertexID;
                    if (TryGetVertexID(r + rowTransformation, c + columnTransformation,
                                       out movedToVertexID))
                    {
                        _knightMoveGraph.AddEdge(thisVertexID, movedToVertexID);
                    }
                }
            }
        }
    }
        public void TestDoubleBreadthA_1()
        {
            SimpleGraph <int>    graph = GetGraphB();
            List <Vertex <int> > list  = graph.BreadthFirstSearch(2, 5);
            List <Vertex <int> > list2 = graph.BreadthFirstSearch(3, 8);
            List <Vertex <int> > list3 = graph.BreadthFirstSearch(1, 5);

            int[] array  = new int[] { 2, 0, 4, 5 };
            int[] array3 = new int[] { 1, 9, 5 };

            int index = 0;

            foreach (Vertex <int> vert in list)
            {
                Assert.AreEqual(array[index++], vert.Value);
            }

            Assert.AreEqual(0, list2.Count);

            index = 0;
            foreach (Vertex <int> vert in list3)
            {
                Assert.AreEqual(array3[index++], vert.Value);
            }
        }
Ejemplo n.º 18
0
        public void ValidatesAGraph1()
        {
            // This graph is a triangle.
            var graph = SimpleGraph.CreateFromZeroBasedEdges(3, new[, ]
            {
                { 0, 1 }, { 0, 2 }, { 1, 2 }
            });

            Assert.AreEqual(2, graph.Vertices[0].Degree);
            Assert.AreEqual(2, graph.Vertices[1].Degree);
            Assert.AreEqual(2, graph.Vertices[2].Degree);

            Assert.IsTrue(graph.HasEdge(0, 1));
            Assert.IsTrue(graph.HasEdge(1, 0));
            Assert.IsTrue(graph.HasEdge(0, 2));
            Assert.IsTrue(graph.HasEdge(1, 2));
            Assert.IsFalse(graph.HasEdge(1, 1));

            Assert.IsFalse(graph.Vertices[0].HasNeighbor(0));
            Assert.IsTrue(graph.Vertices[0].HasNeighbor(1));
            Assert.IsTrue(graph.Vertices[0].HasNeighbor(2));

            Assert.IsTrue(graph.Vertices[1].HasNeighbor(0));
            Assert.IsFalse(graph.Vertices[1].HasNeighbor(1));
            Assert.IsTrue(graph.Vertices[1].HasNeighbor(2));

            Assert.IsTrue(graph.Vertices[2].HasNeighbor(0));
            Assert.IsTrue(graph.Vertices[2].HasNeighbor(1));
            Assert.IsFalse(graph.Vertices[2].HasNeighbor(2));
        }
Ejemplo n.º 19
0
    // The only way to cover a leaf's edge is by choosing the leaf, or by choosing
    // its parent. Choosing its parent is better since that'll cover other edges
    // as well. This solution chooses leaf parents, and removes from the tree any
    // edges the leaf parent covers. As this removal process happens, new leaves
    // get created and set aside to work on. Once there are no more leaves left,
    // we're done. We know this works because assume we missed part of the tree. The
    // part is also a tree, so it has a leaf. This leaf wasn't one of the initial leaves,
    // otherwise we would've seen it already. So to be a leaf now it must've had an
    // edge removed, so it must've been a neighbor of one of the parent leaves,
    // so we must've seen it, contradiction.
    public static int Solve(SimpleGraph tree)
    {
        var leaves          = new HashSet <Vertex>(tree.Vertices.Where(v => v.Degree == 1));
        int vertexCoverSize = 0;

        while (leaves.Any())
        {
            var leaf       = leaves.First();
            var parentLeaf = leaf.Neighbors.First();

            var parentLeafNeighbors = parentLeaf.Neighbors.ToArray();
            foreach (var parentLeafNeighor in parentLeafNeighbors)
            {
                tree.RemoveEdge(parentLeaf, parentLeafNeighor);

                if (parentLeafNeighor.Degree == 1)
                {
                    leaves.Add(parentLeafNeighor);
                }
                else if (parentLeafNeighor.Degree == 0)
                {
                    leaves.Remove(parentLeafNeighor);
                }
            }

            // Parent may have been a leaf, and its degree is 0 now, so try removing.
            leaves.Remove(parentLeaf);

            ++vertexCoverSize;
        }

        return(vertexCoverSize);
    }
Ejemplo n.º 20
0
        public async Task TestSpec2SpecMapGeneratedByTypeChecker(SimpleGraph file2file)
        {
            var helper    = new WorkspaceEvaluationHelper(TestOutputDirectory, null, forTesting: true);
            var repo      = GenerateFullWorkspaceRepo(helper, file2file);
            var workspace = await helper.ParseAsync(repo);

            var semanticModel = helper.Typecheck(workspace);

            Func <int, AbsolutePath> specIdxToSpecPath = (specIdx) => SpecIdxToSpecPath(repo, specIdx);
            var relevantSpecPaths = file2file.Nodes.Select(specIdxToSpecPath).ToList();
            Func <RoaringBitSet, IEnumerable <AbsolutePath> > materializeRelevant = (bitSet) =>
            {
                bitSet.MaterializeSetIfNeeded(string.Empty, (s, i) => workspace.GetAllSourceFiles()[i].GetAbsolutePath(helper.PathTable));
                return(bitSet.MaterializedSetOfPaths.Intersect(relevantSpecPaths));
            };

            // test the spec2spec map generated by TypeChecker
            XAssert.All(
                file2file.Nodes,
                specIdx =>
            {
                var specSourceFile       = workspace.GetSourceFile(SpecIdxToSpecPath(repo, specIdx));
                var computedDependencies = materializeRelevant(semanticModel.GetFileDependenciesOf(specSourceFile));
                var computedDependents   = materializeRelevant(semanticModel.GetFileDependentFilesOf(specSourceFile));
                var expectedDependents   = file2file.OutgoingEdges(specIdx).Select(e => specIdxToSpecPath(e.Dest));
                var expectedDependencies = file2file.IncomingEdges(specIdx).Select(e => specIdxToSpecPath(e.Src));

                XAssert.SetEqual(expectedDependencies, computedDependents);
                XAssert.SetEqual(expectedDependents, computedDependencies);
            });
        }
Ejemplo n.º 21
0
        public static SimpleGraph MakeSandwich(int size)
        {
            SimpleGraph g      = new SimpleGraph();
            int         center = size * 2;

            // face A
            for (int i = 0; i < size - 1; i++)
            {
                g.MakeEdge(i, i + 1);
                g.MakeEdge(i, center);
            }
            g.MakeEdge(size - 1, 0);
            g.MakeEdge(size - 1, center);

            // face B
            for (int i = 0; i < size - 1; i++)
            {
                g.MakeEdge(i + size, i + size + 1);
                g.MakeEdge(i + size, center);
            }
            g.MakeEdge((2 * size) - 1, size);
            g.MakeEdge((2 * size) - 1, center);

            return(g);
        }
Ejemplo n.º 22
0
        public static SimpleGraph MakeGrotschGraph()
        {
            SimpleGraph g = new SimpleGraph();

            g.MakeEdge(0, 1);
            g.MakeEdge(0, 2);
            g.MakeEdge(0, 3);
            g.MakeEdge(0, 4);
            g.MakeEdge(0, 5);
            g.MakeEdge(1, 7);
            g.MakeEdge(1, 10);
            g.MakeEdge(2, 6);
            g.MakeEdge(2, 8);
            g.MakeEdge(3, 7);
            g.MakeEdge(3, 9);
            g.MakeEdge(4, 8);
            g.MakeEdge(4, 10);
            g.MakeEdge(5, 6);
            g.MakeEdge(5, 9);
            g.MakeEdge(6, 7);
            g.MakeEdge(6, 10);
            g.MakeEdge(7, 8);
            g.MakeEdge(8, 9);
            g.MakeEdge(9, 10);
            return(g);
        }
Ejemplo n.º 23
0
        public void TestAddED_RemoveED_3()
        {
            SimpleGraph graph = new SimpleGraph(4);

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

            graph.AddEdge(0, 1);
            graph.AddEdge(0, 2);
            graph.AddEdge(0, 3);
            graph.AddEdge(2, 3);
            Assert.IsFalse(graph.IsEdge(1, 3));
            Assert.IsFalse(graph.IsEdge(1, 2));
            Assert.IsTrue(graph.IsEdge(0, 1));
            Assert.IsTrue(graph.IsEdge(0, 2));
            Assert.IsTrue(graph.IsEdge(0, 3));
            Assert.IsTrue(graph.IsEdge(2, 3));

            graph.RemoveVertex(2);
            Assert.IsTrue(graph.vertex[2] == null);
            Assert.IsFalse(graph.IsEdge(0, 2));
            Assert.IsFalse(graph.IsEdge(2, 0));

            Assert.IsFalse(graph.IsEdge(3, 2));
        }
Ejemplo n.º 24
0
        public void TestAddED_RemoveED_5()
        {
            SimpleGraph graph = new SimpleGraph(3);

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

            graph.AddEdge(0, 1);
            graph.AddEdge(0, 2);
            Assert.IsTrue(graph.m_adjacency[0, 1] == 1);
            Assert.IsTrue(graph.m_adjacency[0, 2] == 1);

            graph.RemoveEdge(0, 2);
            Assert.IsTrue(graph.m_adjacency[0, 1] == 1);
            Assert.IsTrue(graph.m_adjacency[0, 2] == 0);

            graph.AddEdge(2, 0);
            Assert.IsTrue(graph.m_adjacency[0, 1] == 1);
            Assert.IsTrue(graph.m_adjacency[0, 2] == 1);

            graph.RemoveEdge(2, 0);
            Assert.IsTrue(graph.m_adjacency[0, 1] == 1);
            Assert.IsTrue(graph.m_adjacency[2, 0] == 0);
        }
        //Iterative depth-first search that returns the node with the target data.
        public static GraphNode <T> BFS <T>(this SimpleGraph <T> graph, T target)
        {
            if (graph == null || graph.Nodes.Count == 0)
            {
                return(null);
            }

            var visited = new HashSet <GraphNode <T> >();
            var queue   = new DataStructures.Queue <GraphNode <T> >();

            queue.Enqueue(graph.Root);

            while (!queue.IsEmpty)
            {
                GraphNode <T> curr = queue.Dequeue();

                if (visited.Contains(curr))
                {
                    continue;
                }

                if (curr.Data.Equals(target))
                {
                    return(curr);
                }

                visited.Add(curr);
                foreach (GraphNode <T> neighbor in curr.Neighbors)
                {
                    queue.Enqueue(neighbor);
                }
            }

            return(null);
        }
        public void TestBreadthA_Empty()
        {
            SimpleGraph <int>    graph = GetGraphA();
            List <Vertex <int> > list  = graph.BreadthFirstSearch(7, 8);

            Assert.AreEqual(0, list.Count);
        }
        /*
         *          0   1   2   3   4   5   6   7   8   9
         *
         *
         * 0        0   1   1   0   1   0   0   0   0   0
         *
         * 1        1   0   0   0   0   0   0   1   0   1
         *
         * 2        1   0   0   1   0   0   0   0   0   0
         *
         * 3        0   0   1   0   1   0   0   0   0   0
         *
         * 4        1   0   0   1   0   1   0   0   0   0
         *
         * 5        0   0   0   0   1   0   0   0   0   1
         *
         * 6        0   0   0   0   0   0   0   1   0   1
         *
         * 7        0   1   0   0   0   0   1   0   0   0
         *
         * 8        0   0   0   0   0   0   0   0   0   0
         *
         * 9        0   1   0   0   0   1   1   0   0   0
         */
        private SimpleGraph <int> GetGraphB()
        {
            SimpleGraph <int> graph = new SimpleGraph <int>(10);

            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);
            graph.AddVertex(5);
            graph.AddVertex(6);
            graph.AddVertex(7);
            graph.AddVertex(8);
            graph.AddVertex(9);

            graph.AddEdge(0, 1);
            graph.AddEdge(0, 2);
            graph.AddEdge(0, 4);
            graph.AddEdge(1, 7);
            graph.AddEdge(1, 9);
            graph.AddEdge(2, 3);
            graph.AddEdge(3, 4);
            graph.AddEdge(4, 5);
            graph.AddEdge(5, 9);
            graph.AddEdge(6, 7);
            graph.AddEdge(6, 9);

            return(graph);
        }
Ejemplo n.º 28
0
    private static void Main()
    {
        var output    = new StringBuilder();
        int testCount = FastIO.ReadNonNegativeInt();

        for (int t = 1; t <= testCount; ++t)
        {
            int bugCount         = FastIO.ReadNonNegativeInt();
            int interactionCount = FastIO.ReadNonNegativeInt();
            var interactionGraph = new SimpleGraph(bugCount);

            for (int i = 0; i < interactionCount; ++i)
            {
                interactionGraph.AddEdge(
                    firstVertexID: FastIO.ReadNonNegativeInt() - 1,
                    secondVertexID: FastIO.ReadNonNegativeInt() - 1);
            }

            output.AppendLine($"Scenario #{t}:");
            output.AppendLine(BUGLIFE.Solve(interactionGraph)
                ? "No suspicious bugs found!" : "Suspicious bugs found!");
        }

        Console.Write(output);
    }
Ejemplo n.º 29
0
        public static void Main(string[] args)
        {
            var graph = new SimpleGraph <bool>();

            var node1       = new SimpleGraphNode <bool>(1);
            var Node1Input1 = new SimpleGraphTerminal <bool>(node1);
            var Node1Input2 = new SimpleGraphTerminal <bool>(node1);
            var Node1Output = new SimpleGraphTerminal <bool>(node1);

            node1.Inputs.Add(Node1Input1);
            node1.Inputs.Add(Node1Input2);
            node1.Outputs.Add(Node1Output);

            var node2       = new SimpleGraphNode <bool>(2);
            var Node2Input1 = new SimpleGraphTerminal <bool>(node2);
            var Node2Output = new SimpleGraphTerminal <bool>(node2);

            node2.Inputs.Add(Node2Input1);
            node2.Outputs.Add(Node2Output);

            var node3       = new SimpleGraphNode <bool>(3);
            var Node3Input1 = new SimpleGraphTerminal <bool>(node3);
            var Node3Output = new SimpleGraphTerminal <bool>(node3);

            node3.Inputs.Add(Node3Input1);
            node3.Outputs.Add(Node3Output);

            var node4       = new SimpleGraphNode <bool>(4);
            var Node4Output = new SimpleGraphTerminal <bool>(node4);

            node4.Outputs.Add(Node4Output);

            var node5       = new SimpleGraphNode <bool>(5);
            var Node5Output = new SimpleGraphTerminal <bool>(node5);

            node5.Outputs.Add(Node5Output);

            var node6       = new SimpleGraphNode <bool>(6);
            var Node6Input1 = new SimpleGraphTerminal <bool>(node6);

            node6.Inputs.Add(Node6Input1);

            graph.AddNode(node1);
            graph.AddNode(node2);
            graph.AddNode(node3);
            graph.AddNode(node4);
            graph.AddNode(node5);
            graph.AddNode(node6);

            graph.AddEdge(new SimpleGraphEdge <bool>(Node3Output, Node6Input1));
            graph.AddEdge(new SimpleGraphEdge <bool>(Node1Output, Node2Input1));
            graph.AddEdge(new SimpleGraphEdge <bool>(Node2Output, Node3Input1));
            graph.AddEdge(new SimpleGraphEdge <bool>(Node4Output, Node1Input1));
            graph.AddEdge(new SimpleGraphEdge <bool>(Node5Output, Node1Input2));

            graph.CalculateFromNode(node3);

            Console.ReadKey();
        }
Ejemplo n.º 30
0
        public void AddVertex()
        {
            var g = new SimpleGraph(10);

            g.AddVertex(1);
            g.AddVertex(2);

            Assert.True(!g.IsEdge(1, 2));
        }
Ejemplo n.º 31
0
    static PPATH()
    {
        // 10000 because zero-based indices. This isn't great as we don't need 10000
        // (as most #s don't represent primes), but hopefully it doesn't matter. Edges
        // exist between primes (a vertex whose index is prime) and other primes,
        // when there's a one-digit swap to go between them (swaps are reversible).
        _primeGraph = new SimpleGraph(10000);
        var primeDecider = new SieveOfEratosthenesDecider(9999);

        // If n is a prime, connect to the primes greater than it, within a one-digit swap. Only
        // greater than because lesser primes were already connected to it earlier in the loop.
        for (int n = 1001; n <= 9999; n += 2)
        {
            if (!primeDecider.IsOddPrime(n)) continue;

            int nSwapped = n + 1000;
            while (nSwapped % 10000 > n)
            {
                if (primeDecider.IsOddPrime(nSwapped))
                    _primeGraph.AddEdge(n, nSwapped);

                nSwapped += 1000;
            }

            nSwapped = n + 100;
            while (nSwapped % 1000 > n % 1000)
            {
                if (primeDecider.IsOddPrime(nSwapped))
                    _primeGraph.AddEdge(n, nSwapped);

                nSwapped += 100;
            }

            nSwapped = n + 10;
            while (nSwapped % 100 > n % 100)
            {
                if (primeDecider.IsOddPrime(nSwapped))
                    _primeGraph.AddEdge(n, nSwapped);

                nSwapped += 10;
            }

            nSwapped = n + 2;
            while (nSwapped % 10 > n % 10)
            {
                if (primeDecider.IsOddPrime(nSwapped))
                    _primeGraph.AddEdge(n, nSwapped);

                nSwapped += 2;
            }
        }
    }
Ejemplo n.º 32
0
    // For example, edges like (1, 2), (2, 3) => there's an edge between vertices 0 and 1 and 1 and 2.
    public static SimpleGraph CreateFromOneBasedEdges(int vertexCount, int[,] edges)
    {
        var graph = new SimpleGraph(vertexCount);

        for (int id = 0; id < vertexCount; ++id)
        {
            graph._vertices[id] = new Vertex(graph, id);
        }

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

        return graph;
    }
Ejemplo n.º 33
0
 internal Vertex(SimpleGraph graph, int ID)
 {
     _graph = graph;
     this.ID = ID;
 }