Ejemplo n.º 1
0
        public BackToMenuFromDrawButton(AdjacencyList adjacencyList, List <VertexDraw> vertexDraws,
                                        List <EdgeDraw> edgeDraws, StartForm.DrawForm drawForm, AdjacencyListPanel adjacencyListPanel,
                                        WeightTable weightTable, List <List <CellBox> > matrix, List <List <CellAdjacencyList> > cells,
                                        string buttonText = "Menu") : base(buttonText)
        {
            ForeColor = Color.Black;

            this.BackColor = Color.Orange;

            Font = new System.Drawing.Font("Comic Sans MS", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204)));

            FlatStyle = System.Windows.Forms.FlatStyle.Popup;

            Text = buttonText;

            Location = new System.Drawing.Point(300, 410);

            this.adjacencyList = adjacencyList;

            this.vertexDraws = vertexDraws;

            this.edgeDraws = edgeDraws;

            this.drawForm = drawForm;

            this.weightTable = weightTable;

            this.adjacencyListPanel = adjacencyListPanel;

            this.matrix = matrix;

            this.cells = cells;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// BFS made in tree format. Saving information of each node's parent
        /// </summary>
        /// <param name="dg"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static List <int?> BFS_tree(AdjacencyList dg, int startIndex)
        {
            int         cont   = 0;
            List <int?> visit  = new List <int?>();
            List <int?> parent = new List <int?>(); /////////
            List <int>  stack  = new List <int>();

            dg.Digraph.ForEach(_ => { visit.Add(null); parent.Add(null); });
            visit[startIndex]  = cont++;
            parent[startIndex] = startIndex;
            stack.Add(startIndex);
            while (stack.Any())
            {
                int v = stack.First();
                stack.RemoveAt(0);
                for (List <int> a = dg.Digraph[v]; a.Any(); a.RemoveAt(0))
                {
                    if (visit[a.First()] == null)
                    {
                        visit[a.First()]  = cont++;
                        parent[a.First()] = v; ///////////
                        stack.Add(a.First());
                    }
                }
            }
            return(visit);
        }
Ejemplo n.º 3
0
        public Graph ConnectNodes(LocationNode a, LocationNode b)
        {
            var containsA = AdjacencyList.Any(list => list.Contains(a));
            var containsB = AdjacencyList.Any(list => list.Contains(b));

            if (!containsA)
            {
                AddNode(a);
            }
            if (!containsB)
            {
                AddNode(b);
            }

            List <LocationNode>[] rootA = { new List <LocationNode>() };
            List <LocationNode>[] rootB = { new List <LocationNode>() };
            foreach (var list in AdjacencyList.Where(list => list[0] == a && rootA[0].Count == 0))
            {
                rootA[0] = list;
            }
            foreach (var list in AdjacencyList.Where(list => list[0] == b && rootB[0].Count == 0))
            {
                rootB[0] = list;
            }

            rootA[0].Add(b);
            rootB[0].Add(a);

            return(this);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Dijkstra is an optimal algorithm for finding the shortest path in a digraph that has all positive ark values.
        /// </summary>
        /// <param name="dg"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static List <double> Dijkstra(AdjacencyList dg, int startIndex)
        {
            List <int?>   parent = new List <int?>();
            List <double> costs  = new List <double>();
            List <int>    stack  = new List <int>();

            dg.Digraph.ForEach(_ => { parent.Add(null); costs.Add(double.MaxValue); });
            costs[startIndex]  = 0;
            parent[startIndex] = startIndex;
            stack.Add(startIndex);
            while (stack.Any())
            {
                int node = stack.First();
                stack.Remove(node);
                foreach (var ark in dg.WeightedDigraph.OrderBy(x => x.value).Where(x => x.initialNode == node))
                {
                    if (costs[ark.finalNode] == double.MaxValue)
                    {
                        parent[ark.finalNode] = ark.initialNode;
                        costs[ark.finalNode]  = costs[ark.initialNode] + ark.value;
                        stack.Add(ark.finalNode);
                    }
                    else if (costs[ark.finalNode] > costs[ark.initialNode] + ark.value)
                    {
                        parent[ark.finalNode] = ark.initialNode;
                        costs[ark.finalNode]  = costs[ark.initialNode] + ark.value;
                    }
                }
            }

            return(costs);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Minimal path finder algorithm when not all arks have positive values.
        /// </summary>
        /// <param name="dg"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static List <double> Bellman_Ford(AdjacencyList dg, int startIndex)
        {
            List <int?>   parent = new List <int?>();
            List <double> dist   = new List <double>();

            dg.Digraph.ForEach(x => {
                parent.Add(null);
                dist.Add(double.MaxValue);
            });
            parent[startIndex] = startIndex;
            dist[startIndex]   = 0;

            for (int i = 0; i < dg.Digraph.Count; i++)
            {
                foreach (var ark in dg.WeightedDigraph)
                {
                    RELAX(ark, ref parent, ref dist);
                }
            }
            if (verifyCicloNegativo(dg, ref dist))
            {
                return(dist);
            }
            else
            {
                return(new List <double>());
            }
        }
Ejemplo n.º 6
0
        public Graph ConvertToGraph(AdjacencyList adjacencyList)
        {
            Graph  graph  = new Graph();
            Vertex vertex = new Vertex();

            graph.Vertexs = new List <Vertex>(adjacencyList.adjacencyList.Count);

            for (int i = 0; i < adjacencyList.adjacencyList.Count; i++)
            {
                vertex.Nodes = new List <Node>(adjacencyList.adjacencyList[i].Count);

                for (int j = 0; j < adjacencyList.adjacencyList[i].Count; j++)
                {
                    vertex.Nodes.Add(new Node()
                    {
                        Weight = adjacencyList.adjacencyList[i][j].Weight, Connectable = adjacencyList.adjacencyList[i][j].Connectable
                    });
                }

                graph.Vertexs.Add(new Vertex()
                {
                    Nodes = vertex.Nodes, Id = i
                });
            }

            return(graph);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Digraph Distance calculation. The metrics in this method is quantity of nodes or 'steps'. Not a valued distance
        /// </summary>
        /// <param name="dg"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static List <int?>[] DIGRAPHdist(AdjacencyList dg, int startIndex)
        {
            List <int?> dist   = new List <int?>();
            List <int?> parent = new List <int?>();
            List <int>  stack  = new List <int>();

            dg.Digraph.ForEach(_ => { dist.Add(null); parent.Add(null); });
            dist[startIndex]   = 0;
            parent[startIndex] = startIndex;
            stack.Add(startIndex);
            while (stack.Any())
            {
                List <int> a;
                int        v = stack.First();
                stack.RemoveAt(0);
                for (a = dg.Digraph.First(); a.Any(); a.RemoveAt(0))
                {
                    if (dist[a.First()] == null)
                    {
                        dist[a.First()]   = dist[v] + 1;
                        parent[a.First()] = v;
                        stack.Add(a.First());
                    }
                }
            }
            return(new List <int?>[] { dist, parent });
        }
Ejemplo n.º 8
0
        static LinkedList <int> SearchConnectedComponent(AdjacencyList list, int source, ref bool[] checkpoint)
        {
            var q = new Queue <int>();

            q.Enqueue(source);
            checkpoint[source] = true;
            var tmp = new LinkedList <int>();

            tmp.AddLast(source);
            while (q.Count != 0)
            {
                source = q.Dequeue();
                foreach (var item in list.List[source])
                {
                    if (checkpoint[item])
                    {
                        continue;
                    }
                    checkpoint[item] = true;
                    tmp.AddLast(item);
                    q.Enqueue(item);
                }
            }
            return(tmp);
        }
        public DeleteAllButton(int width, int height, AdjacencyList adjacencyList, List <VertexDraw> vertexDraws,
                               List <EdgeDraw> edgeDraws, StartForm.DrawForm drawForm, AdjacencyListPanel adjacencyListPanel,
                               WeightTable weightTable, List <List <CellBox> > matrix, List <List <CellAdjacencyList> > cells)
        {
            Size = new System.Drawing.Size(width, height);

            Dock = DockStyle.Top;

            Text = "Delete all";

            Click += new EventHandler(ButtonClick);

            this.adjacencyList = adjacencyList;

            this.vertexDraws = vertexDraws;

            this.edgeDraws = edgeDraws;

            this.drawForm = drawForm;

            this.weightTable = weightTable;

            this.adjacencyListPanel = adjacencyListPanel;

            this.matrix = matrix;

            this.cells = cells;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Check bridges
        /// </summary>
        /// <param name="list"></param>
        static void Process1(AdjacencyList list)
        {
            int n = FindConnectedComponent(list).Count();

            for (int i = 0; i < list.List.Length; i++)
            {
                foreach (var item in list.List[i])
                {
                    var tmp = DeepCopy(list);

                    // 1. Remove the edge
                    tmp.List[i].Remove(item);
                    tmp.List[item].Remove(i);

                    // 2. Counting connected components
                    int m = FindConnectedComponent(tmp).Count();

                    // 3. Comparing and printing result
                    if (m > n)
                    {
                        WriteLine($"[{i}, {item}] is a brigde");
                    }
                    else
                    {
                        WriteLine($"[{i}, {item}] is not a brigde");
                    }
                }
            }

            WriteLine();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Check articulation points
        /// </summary>
        /// <param name="list"></param>
        static void Process2(AdjacencyList list)
        {
            int n = FindConnectedComponent(list).Count();

            for (int i = 0; i < list.List.Length; i++)
            {
                var tmp = DeepCopy(list);

                // 1. Remove the vertex
                tmp.List[i].Clear();

                // 2. Remove the edges that connect to the vertex
                for (int j = 0; j < tmp.Vertices; j++)
                {
                    tmp.List[j].Remove(i);
                }

                // 3. Decrease 1: not counting the connected-component of removed-vertex
                int m = FindConnectedComponent(tmp).Count() - 1;

                // Compare and print result
                if (m > n)
                {
                    WriteLine($"Vertex[{i}] is a articulation point");
                }
                else
                {
                    WriteLine($"Vertex[{i}] is not a articulation point");
                }
            }

            WriteLine();
        }
    void CallGraph()
    {
        graph = DungeonMapData.data[location];
        //eventMap = DungeonMapData.lectureEvents;
        //eventCatcher = gameObject.transform.parent.parent.GetComponent<Dungeon>();
        graph.unityView = this;

        foreach (Transform child in gameObject.transform)
        {
            AdjacencyList edges   = graph.edges[child.gameObject.GetComponent <RoomNode>().ID];
            string        fromKey = edges.self;
            Vector3       fromPos = gameObject.transform.Find(fromKey).position;
            foreach (string toKey in edges.destinations)
            {
                Vector3    toPos = gameObject.transform.Find(toKey).position;
                GameObject line  = Instantiate(edgeLine, edgeSpace);
                line.transform.position   = new Vector3((fromPos.x + toPos.x) / 2, (fromPos.y + toPos.y) / 2, 0);
                line.transform.localScale = new Vector3(1, (float)System.Math.Sqrt(System.Math.Pow(fromPos.x - toPos.x, 2)
                                                                                   + System.Math.Pow(fromPos.y - toPos.y, 2) + System.Math.Pow(fromPos.z - toPos.z, 2)) / 150, 1);
                //Debug.Log(line.transform.localScale.ToString());
                if (toPos.x - fromPos.x != 0 && toPos.y - fromPos.y != 0)
                {
                    line.transform.Rotate(new Vector3(0, 0, (float)(-1 * (90 - System.Math.Atan((toPos.y - fromPos.y) / (toPos.x - fromPos.x)) * 180 / 3.14))));
                    //Debug.Log(System.Math.Acos((toPos.x - fromPos.x) / (toPos.y - fromPos.y)).ToString());
                }
                else if (toPos.y - fromPos.y == 0)
                {
                    line.transform.Rotate(new Vector3(0, 0, 90));
                }
                //line.transform.SetAsFirstSibling();
            }
        }
    }
Ejemplo n.º 13
0
        public void ShortestPathSearcher_Integration_DefaultAggregativeWeight()
        {
            string vertexA = "A", vertexB = "B", vertexC = "C", vertexD = "D";

            // Graph A-B, A-C, B-D, B-A
            AdjacencyList <string, int> graph = new AdjacencyList <string, int>();

            graph.AddVertex(vertexA);
            graph.AddVertex(vertexB);
            graph.AddVertex(vertexC);
            graph.AddVertex(vertexD);
            graph.AddEdge(vertexA, vertexB, 10);
            graph.AddEdge(vertexB, vertexA, 5);
            graph.AddEdge(vertexA, vertexC, 20);
            graph.AddEdge(vertexB, vertexD, 10);

            ShortestPathSearcher <string, int>          searcher = new ShortestPathSearcher <string, int>(graph, vertexA, vertexD, (i) => i);
            IEnumerable <EdgeDescriptor <string, int> > path = searcher.FindShortestPath();

            Assert.IsNotNull(path);
            Assert.AreEqual(2, path.Count());
            EdgeDescriptor <string, int> firstDesc = path.First();

            Assert.AreEqual("B", firstDesc.Vertex1);
            Assert.AreEqual("A", firstDesc.Vertex2);
            Assert.AreEqual(5, firstDesc.Edge);
            EdgeDescriptor <string, int> lastDesc = path.Last();

            Assert.AreEqual("B", lastDesc.Vertex1);
            Assert.AreEqual("D", lastDesc.Vertex2);
            Assert.AreEqual(10, lastDesc.Edge);
        }
Ejemplo n.º 14
0
        public void ShortestPathSearcher_Integration_CumulativeWeight()
        {
            string vertexA = "A", vertexB = "B", vertexC = "C";

            // Graph A-B=2, A-C=3, B-C=4
            AdjacencyList <string, int> graph = new AdjacencyList <string, int>();

            graph.AddVertex(vertexA);
            graph.AddVertex(vertexB);
            graph.AddVertex(vertexC);
            graph.AddEdge(vertexA, vertexB, 2);
            graph.AddEdge(vertexA, vertexC, 3);
            graph.AddEdge(vertexB, vertexC, 4);

            ShortestPathSearcher <string, int> searcher = new ShortestPathSearcher <string, int>(graph, vertexB, vertexC, (i) => i)
            {
                PathWeightCalculation = PathWeightCalculationType.Cumulative
            };
            IEnumerable <EdgeDescriptor <string, int> > path = searcher.FindShortestPath();

            Assert.IsNotNull(path);
            Assert.AreEqual(2, path.Count());
            EdgeDescriptor <string, int> edge1 = path.First();

            Assert.AreEqual("A", edge1.Vertex1);
            Assert.AreEqual("B", edge1.Vertex2);
            Assert.AreEqual(2, edge1.Edge);
            EdgeDescriptor <string, int> edge2 = path.Last();

            Assert.AreEqual("A", edge2.Vertex1);
            Assert.AreEqual("C", edge2.Vertex2);
            Assert.AreEqual(3, edge2.Edge);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Computes and assigns a dimensionfactor to all nodes which appear in an adjacencylist
        /// The dimensionfactor is a float value between 0 and 1 and states
        /// the indegree/outdegree ratio a node has in its dimensionlayer. This value can be used
        /// by frontend applications to easily position the objects
        /// </summary>
        /// <remarks>A visual example is given in the related testproject</remarks>
        internal static void ComputeDimensionFactors(AdjacencyList adjacencyList)
        {
            foreach (var group in adjacencyList.Groups)
            {
                foreach (var edge in group.Value.Edges)
                {
                    Queue <Node> sourceStack = new Queue <Node>();
                    Queue <Node> targetStack = new Queue <Node>();
                    GetUpperTreePart(sourceStack, edge.Value.Source);
                    GetUpperTreePart(targetStack, edge.Value.Target);

                    while (sourceStack.Count > targetStack.Count)
                    {
                        sourceStack.Dequeue();
                    }
                    while (targetStack.Count > sourceStack.Count)
                    {
                        targetStack.Dequeue();
                    }

                    while (true)
                    {
                        Node currentSource = sourceStack.Dequeue();
                        Node currentTarget = targetStack.Dequeue();

                        if (sourceStack.Count == 0 || sourceStack.Peek().Id.Equals(targetStack.Peek().Id))
                        {
                            currentSource.IsSource();
                            currentTarget.IsTarget();
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public void AdjacencyList_Filter_SelectesPartOfVertices()
        {
            int    vertex1 = 10;
            int    vertex2 = 20;
            int    vertex3 = 30;
            int    vertex4 = 40;
            string edge1   = "20-30";
            string edge2   = "30-40";

            AdjacencyList <int, string> adjacencyList = new AdjacencyList <int, string>();

            adjacencyList.AddVertex(vertex1);
            adjacencyList.AddVertex(vertex2);
            adjacencyList.AddVertex(vertex3);
            adjacencyList.AddVertex(vertex4);
            adjacencyList.AddEdge(vertex2, vertex3, edge1);
            adjacencyList.AddEdge(vertex3, vertex4, edge2);

            IGraph <int, string> filtered = adjacencyList.Filter((v1, v2, ed) => v1 == 20);

            Assert.Equal(2, filtered.NumVertices);
            Assert.True(filtered.HasVertex(vertex2));
            Assert.True(filtered.HasVertex(vertex3));
            Assert.Equal(edge1, filtered.FindEdge(vertex2, vertex3));
        }
        public void GetEdgesFrom_ShouldReturnAllEdgesStartingFromStartVertex()
        {
            var startVertex = 'C';
            var expected    = new List <DirectedEdge>
            {
                new DirectedEdge(startVertex, 'D', 6)
                , new DirectedEdge(startVertex, 'E', 8)
                , new DirectedEdge(startVertex, 'A', 1)
            };

            var target = new AdjacencyList();

            foreach (var edge in expected)
            {
                target.AddDirectedEdge(edge);
            }

            var actual = target.GetEdgesFrom(startVertex);

            for (var i = 0; i < actual.Count; i++)
            {
                Assert.That(actual[i].StartVertex, Is.EqualTo(expected[i].StartVertex));
                Assert.That(actual[i].EndVertex, Is.EqualTo(expected[i].EndVertex));
                Assert.That(actual[i].Weight, Is.EqualTo(expected[i].Weight));
            }
        }
        public void Load_Empty_List()
        {
            int expected = 0;
            AdjacencyList list = new AdjacencyList("empty.txt");

            Assert.AreEqual(expected, list.Count);
        }
        public void Load_Trash_List()
        {
            int expected = 0;
            AdjacencyList list = new AdjacencyList("trash.txt");

            Assert.Inconclusive();
        }
        public void Load_2x2_List()
        {
            int expected = 4;
            AdjacencyList list = new AdjacencyList("2x2onecolor.txt");

            Assert.AreEqual(expected, list.Count);
        }
        public void Load_3x3_List()
        {
            int expected = 9;
            AdjacencyList list = new AdjacencyList("3x3.txt");

            Assert.AreEqual(expected, list.Count);
        }
Ejemplo n.º 22
0
        public void AdjacencyList_RemoveVertex_RemovesVerticesWithEdges()
        {
            int    vertex1 = 10;
            int    vertex2 = 20;
            int    vertex3 = 30;
            int    vertex4 = 40;
            string edge1   = "20-30";
            string edge2   = "30-40";

            AdjacencyList <int, string> adjacencyList = new AdjacencyList <int, string>();

            adjacencyList.AddVertex(vertex1);
            adjacencyList.AddVertex(vertex2);
            adjacencyList.AddVertex(vertex3);
            adjacencyList.AddVertex(vertex4);
            adjacencyList.AddEdge(vertex2, vertex3, edge1);
            adjacencyList.AddEdge(vertex3, vertex4, edge2);

            Assert.Equal(4, adjacencyList.NumVertices);
            Assert.Equal(edge1, adjacencyList.FindEdge(vertex2, vertex3));
            Assert.Equal(edge2, adjacencyList.FindEdge(vertex3, vertex4));

            adjacencyList.RemoveVertex(vertex2);

            Assert.Equal(3, adjacencyList.NumVertices);
            Assert.Equal(edge2, adjacencyList.FindEdge(vertex3, vertex4));
        }
Ejemplo n.º 23
0
        static bool CheckBipartite(AdjacencyList list, int source, ref bool[] checkpoint, ref int[] flag)
        {
            foreach (var item in list.List[source])
            {
                if (!checkpoint[item])
                {
                    checkpoint[item] = true;
                    if (flag[source] == 0)
                    {
                        flag[item] = 1;
                    }
                    else
                    {
                        flag[item] = 0;
                    }
                    if (!CheckBipartite(list, item, ref checkpoint, ref flag))
                    {
                        return(false);
                    }
                }

                // If the vertex item is traversed
                else if (flag[source] == flag[item])
                {
                    return(false);
                }
            }

            // In the end, if there is nothing happened, return true
            return(true);
        }
Ejemplo n.º 24
0
        private void setList(List <List <int> > data)
        {
            AdjacencyList al = new AdjacencyList();

            data = al.ParseFile <int>(globals.Filepath);

            graph.setData(data);

            vertices_count = graph.getData <int>().Count;

            graph.VerticesAmount = vertices_count;

            //number of vertices to be colored
            color_array = new int[vertices_count];
            //number of vertices which each of vertex represented by the list index and the value is the component class number
            connected_comps = new int[vertices_count];

            Dispatcher.Invoke(new Action(() =>
            {
                if (algorithms.isBipartite <int>(graph, vertices_count, color_array, GraphTypes.Sparse, connected_comps))
                {
                    setViewBI();
                }
                else
                {
                    setViewNotBi();
                }
                MainViewModel.getInstance().ProgressText = "Adjacency list loaded successfully!";
                MainViewModel.getInstance().ProgressVal  = 50;
            }));
        }
Ejemplo n.º 25
0
        public void ConvertToSimpleGrapgTest_ThreeVertexList_GraphThreeVertex()
        {
            List <Vertex> vertices = new List <Vertex> {
                new Vertex {
                    Id = 1, Nodes = new List <Node> {
                        new Node {
                            Connectable = 0, Weight = 12
                        }, new Node {
                            Connectable = 2, Weight = 10
                        }
                    }
                },
                new Vertex {
                    Id = 0, Nodes = new List <Node> {
                        new Node {
                            Connectable = 2, Weight = 5
                        }
                    }
                },
                new Vertex {
                    Id = 2, Nodes = new List <Node>()
                }
            };
            AdjacencyList adjacencyList = new AdjacencyList(vertices);

            List <List <int> > graph = converter.ConvertToSimpleGraph(adjacencyList);

            Assert.IsTrue(graph[0].SequenceEqual(new List <int> {
                2
            }) &&
                          graph[1].SequenceEqual(new List <int> {
                0, 2
            }) && graph[2].SequenceEqual(new List <int>()));
        }
Ejemplo n.º 26
0
        public void VertexFind(NewEdgeDefinition vertexClick, MouseEventArgs e, List <VertexDraw> vertexDraws, List <EdgeDraw> edgeDraws, ref int startVertexId, ref int endVertexId,
                               ref AdjacencyList adjacencyList, AdjacencyListPanel adListPanel, MatrixWeightPanel matrixWeightPanel)
        {
            vertexClick.VertexRemember(ref startVertexId, ref endVertexId
                                       , e.X - (int)VertexParameters.Radius, e.Y - (int)VertexParameters.Radius
                                       , vertexDraws);


            if ((startVertexId != -1) && (endVertexId != -1) && (startVertexId != endVertexId) && (!IsDuplicate(edgeDraws, startVertexId, endVertexId)))
            {
                EdgeDraw edgeDraw = new EdgeDraw(BrushColor.Black, 0, startVertexId, endVertexId);

                edgeDraws.Add(edgeDraw);

                adjacencyList.AddNode(startVertexId, endVertexId, 1);

                adListPanel.UpdateNodesPanel(startVertexId, endVertexId);

                matrixWeightPanel.UpdateNodes(startVertexId, endVertexId);

                startVertexId = -1;
                endVertexId   = -1;
            }
            else if (IsDuplicate(edgeDraws, startVertexId, endVertexId))
            {
                startVertexId = -1;
                endVertexId   = -1;
            }
        }
Ejemplo n.º 27
0
    public static void Solve()
    {
        var n  = I;
        var m  = I;
        var l  = new int[m];
        var r  = new int[m];
        var d  = new long[m];
        var gr = new AdjacencyList <long>(n);

        Repeat(m, i =>
        {
            l[i] = I - 1;
            r[i] = I - 1;
            d[i] = L;
            gr.Add(l[i], r[i], d[i]);
            gr.Add(r[i], l[i], -d[i]);
        });

        var x = new long[n];

        foreach (var edge in gr.DepthFirstSearch())
        {
            x[edge.Target] = x[edge.Source] + edge.Cost;
        }

        Repeat(m, j => { if (x[r[j]] - x[l[j]] != d[j])
                         {
                             Answer(No);
                         }
               });
        Answer(Yes);
    }
        /// <summary>
        /// テスト用メインメソッド
        /// </summary>
        public static void Main(string[] args)
        {
            // AdjacencyList graph = ReadGraph(Common.INSTANCE_PATH + @"undirected_sample.grp");
            AdjacencyList graph = ReadGraph(Common.INSTANCE_PATH + @"directed_sample.grp");

            Console.WriteLine("n : " + graph.NodeNum);
            Console.WriteLine("m : " + graph.EdgeNum);
            foreach (int[] edge in graph.EdgeList)
            {
                Console.WriteLine(edge[0] + "," + edge[1]);
            }

            Console.WriteLine("\n===== in =====");
            for (int i = 0; i < graph.NodeNum; i++)
            {
                Console.WriteLine("===" + i + "===");
                for (LinkNode node = graph.GetInLinkedEdgeList(i).head; node != null; node = node.next)
                {
                    Console.WriteLine(node.data);
                }
            }

            Console.WriteLine("\n===== out =====");
            for (int i = 0; i < graph.NodeNum; i++)
            {
                Console.WriteLine("===" + i + "===");
                for (LinkNode node = graph.GetOutLinkedEdgeList(i).head; node != null; node = node.next)
                {
                    Console.WriteLine(node.data);
                }
            }
        }
Ejemplo n.º 29
0
        public DFSTest()
        {
            AdjacencyList <int> adjacencyList = new AdjacencyList <int>();
            ForDFSNode <int>    firstHead     = new ForDFSNode <int> {
                Data = 1
            };
            ForDFSNode <int> secondHead = new ForDFSNode <int> {
                Data = 2
            };
            ForDFSNode <int> thirdHead = new ForDFSNode <int> {
                Data = 3
            };
            ForDFSNode <int> forthHead = new ForDFSNode <int> {
                Data = 4
            };

            adjacencyList.Nodes.AddRange(new List <ForDFSNode <int> > {
                firstHead, secondHead, thirdHead, forthHead
            });
            adjacencyList.NeighborsList.Add(firstHead, new List <Node <int> > {
                secondHead, forthHead
            });
            adjacencyList.NeighborsList.Add(secondHead, new List <Node <int> > {
                firstHead, thirdHead, forthHead
            });
            adjacencyList.NeighborsList.Add(thirdHead, new List <Node <int> > {
                secondHead, forthHead
            });
            adjacencyList.NeighborsList.Add(forthHead, new List <Node <int> > {
                firstHead, secondHead, thirdHead
            });
            _dfs = new DFS <int>(adjacencyList);
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            AdjacencyList lst = new AdjacencyList(7);

            lst.AddUndirectedArk(0, 2, 5);
            lst.AddUndirectedArk(0, 3, 8);
            lst.AddUndirectedArk(2, 3, 10);
            lst.AddUndirectedArk(2, 1, 16);
            lst.AddUndirectedArk(2, 4, 3);
            lst.AddUndirectedArk(3, 4, 2);
            lst.AddUndirectedArk(3, 5, 18);
            lst.AddUndirectedArk(4, 1, 30);
            lst.AddUndirectedArk(4, 5, 12);
            lst.AddUndirectedArk(4, 6, 14);
            lst.AddUndirectedArk(1, 6, 26);
            lst.AddUndirectedArk(5, 6, 4);

            var pre = Common.Helper.Kruskal(lst);

            lst.Show();

            Console.WriteLine("Pre vector: ");
            for (int i = 0; i < pre.Count; i++)
            {
                Console.Write($"[{i}] ");
            }
            Console.WriteLine();
            pre.ForEach(x =>
            {
                Console.Write($" {x}  ");
            });

            System.Console.ReadKey();
        }
Ejemplo n.º 31
0
        public static bool JudgeEulerian(AdjacencyList graph)
        {
            // 連結性判定
            int[] cc = GraphScanning.CalcDepth(graph, 0);
            if (cc.Length != graph.NodeNum)
            {
                return(false);
            }

            // 有向グラフ
            if (graph.IsDirected)
            {
                // 全てのノードにおいて、入次数と出次数が同じならオイラーグラフ
                for (int i = 0; i < graph.NodeNum; i++)
                {
                    // Inリストのノード数が入次数
                    LinkList list     = graph.GetInLinkedEdgeList(i);
                    int      in_count = 0;
                    for (LinkNode node = list.head; node != null; node = node.next)
                    {
                        in_count++;
                    }
                    // Outリストのノード数が出次数
                    list = graph.GetOutLinkedEdgeList(i);
                    int out_count = 0;
                    for (LinkNode node = list.head; node != null; node = node.next)
                    {
                        out_count++;
                    }

                    // 入次数と出次数が異なるなら終了
                    if (in_count != out_count)
                    {
                        return(false);
                    }
                }
                // 無向グラフの場合
            }
            else
            {
                // 全てのノードの次数が偶数ならオイラーグラフ
                for (int i = 0; i < graph.NodeNum; i++)
                {
                    // リストのノード数が次数
                    LinkList list  = graph.GetInLinkedEdgeList(i);
                    int      count = 0;
                    for (LinkNode node = list.head; node != null; node = node.next)
                    {
                        count++;
                    }
                    // 次数が奇数なら終了
                    if (count % 2 != 0)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 32
0
        public void TestGetEdgesEmptyGraph()
        {
            AdjacencyList <int> graph = new AdjacencyList <int>();

            bool thrown = false;

            for (int i = 0; i < 100; i++)
            {
                try
                {
                    graph.GetEdges(i);
                }
                catch (KeyNotFoundException)
                {
                    thrown = true;
                }

                if (!thrown)
                {
                    Assert.Fail("Exception not thrown");
                }
            }

            Assert.Pass();
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Clones a Node by pointing to the same memebers
        /// </summary>
        /// <param name="node"></param>
        ///
        public Node(INode <KEY> node)
        {
            if (node == null)
            {
                return;
            }

            _key        = node.Key;
            _data       = node.Data;
            _properties = node.Properties;

            Node <KEY> nodeT = node as Node <KEY>;

            if (nodeT != null)
            {
                _edges         = nodeT._edges;
                _adjacencyList = nodeT._adjacencyList;
            }
            else
            {
                foreach (INode <KEY> n in node.AdjacentNodes)
                {
                    AdjacencyList.Add(n);
                }

                foreach (IEdge <KEY> edge in node.EdgeSet)
                {
                    Edges.Add(new KeyValuePair <EdgeKey <KEY>, IEdge <KEY> >(new EdgeKey <KEY>(edge.SourceNode.Key, edge.TargetNode.Key), edge));
                }
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Designed to compute the Strongly Connected Components
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="startNode"></param>
        /// <param name="nodeOrder"></param>
        public DepthFirstSearch(AdjacencyList <TNode, TWeight> graph, List <TNode> nodeOrder)
        {
            if (!graph.HasTheNode(startNode))
            {
                throw new NotImplementedException();
            }

            this.InitializeMembers(graph, nodeOrder[0]);

            foreach (TNode node in graph)
            {
                this.searchResult.AddNode(node);

                labels.Add(node, new FastDepthFirstSearchNode <TNode>(node, null, null));
            }

            int time = 0;

            foreach (TNode node in nodeOrder)
            {
                if (labels[node].IsWhite())
                {
                    Visit(node, ref time);
                }
            }
        }
        public void AdjacencyList_Should_Be_Equal_To_Colored_Vertices()
        {
            AdjacencyList list = new AdjacencyList("2x2onecolor.txt");
            var colorsLine = File.ReadLines("2x2onecolor.txt").First();
            var colors = colorsLine.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(short.Parse);

            Assert.AreEqual(list.Count(), colors.Count());
        }
        public void DontColorMyMatrix()
        {
            AdjacencyList list = new AdjacencyList("2x2onecolor.txt");
            var colorsLine = File.ReadLines("2x2onecolor.txt").First();
            var colors = colorsLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(short.Parse);

            IGraphTraversal traversal = new MatrixTraversal(list, colors.ToArray());
            IColorator colorator = new MatrixColorator(traversal);
            colorator.Color();
        }
Ejemplo n.º 37
0
        public Node(string key, object data, AdjacencyList neighbors)
        {
            Key = key;
            Data = data;

            if (neighbors == null)
            {
                Neighbors = new AdjacencyList();
            }
            else
            {
                Neighbors = neighbors;
            }
        }
Ejemplo n.º 38
0
        public Node(string key, object data, double latitude, double longitude, AdjacencyList neighbors)
        {
            Key = key;
            Data = data;
            Latitude = latitude;
            Longitude = longitude;

            if (neighbors == null)
            {
                Neighbors = new AdjacencyList();
            }
            else
            {
                Neighbors = neighbors;
            }
        }
        public void Initialize(AdjacencyList list, short[] clr)
        {
            if (list == null || clr == null)
            {
                throw new ArgumentException("Input parameters shouldn't be null");
            }

            adjacencyList = list;
            // markedVertices = new bool[adjacencyList.Count + 1];
            verticesColoring = new short[clr.Count() + 1];

            // some extra reindexing operation just for comfort
            for (int i = 1; i < verticesColoring.Count(); i++)
            {
                verticesColoring[i] = clr[i - 1];
            }
        }
Ejemplo n.º 40
0
        private static void BellmanFord()
        {
            var directedGraph = new AdjacencyList(5);
            directedGraph.Add(1, 2, 1);
            directedGraph.Add(1, 1, 4);         // bellman-ford accepts cycles, And negative weights too. //
            directedGraph.Add(2, 3, -5);
            directedGraph.Add(3, 4, -2);
            directedGraph.Add(4, 0, 2);
            directedGraph.Add(4, 3, -2);

            var bF = new BellmanFord();
            bF.Compute(directedGraph, 1);
            for (int i = 0; i < bF.Shortest.Length; i++)
                Console.WriteLine("\t {0} +  -> Weights : [{1}]", i, bF.Shortest[i]);

            Console.WriteLine("\nPredessors: ");
            for (int i = 0; i < bF.Predecessors.Length; i++)
            {
                var pred = bF.Predecessors[i];
                Console.WriteLine("pred[{0}] : {1}", i, pred != null ? pred.ToString() : "NULL");
            }

            Console.WriteLine("Negative Cycle :");
            bF.FindNegativeWeightCycle(directedGraph).ForEach(i => Console.Write(i + " -> "));
            Console.WriteLine();
        }
Ejemplo n.º 41
0
        public static void Dag()
        {
            var dag = new AdjacencyMatrix(5);
            dag.Add(0, 2);
            dag.Add(1, 4);
            dag.Add(6, 3); // Bad Input .. nothing //
            dag.Add(3, 4);
            Console.WriteLine("\n " + dag);

            Console.WriteLine("Topological Sort result :");
            var l = DagAlgorithms.TopologicalSort(dag);
            l.ForEach((i) => Console.WriteLine(i));

            var dag2 = new AdjacencyList(5);
            dag2.Add(0, 2, 1);
            dag2.Add(1, 4, 10);
            dag2.Add(2, 3, 5);
            dag2.Add(3, 1, 2);
            dag2.Add(3, 4, 1);
            Console.WriteLine(dag2);

            Console.WriteLine("\t Vertices: " + dag2.N + "\n\t Edges: " + dag2.M);
            Console.WriteLine("\nTopological Sort result :");
            var l1 = DagAlgorithms.TopologicalSort(dag2);
            l1.ForEach((i) => Console.WriteLine(i));

            // test removing an edge .. //
            dag2.Remove(1, 4);
            Console.WriteLine(dag2);
            Console.WriteLine("\nTopological Sort result :");
            var l2 = DagAlgorithms.TopologicalSort(dag2);
            l2.ForEach((i) => Console.WriteLine(i));

            Console.WriteLine("Shortest Path: ");
            var dagAlgo = new DagAlgorithms();
            dagAlgo.ShortestPath(dag2, 0);

            for (int i = 0; i < dagAlgo.Shortest.Length; i++)
                Console.WriteLine("\t {0} +  -> Weights : [{1}]", i, dagAlgo.Shortest[i]);

            Console.WriteLine("\nPredessors: ");
            for (int i = 0; i < dagAlgo.Predecessors.Length; i++)
            {
                var pred = dagAlgo.Predecessors[i];
                Console.WriteLine("pred[{0}] : {1}", i, pred != null ? pred.ToString() : "NULL");
            }

            var dagTime = new AdjacencyList(5); // Or AdjacencyMatrix(5) //
            dagTime.Add(1, 2, 2.5);
            dagTime.Add(1, 3, 5);
            dagTime.Add(3, 4, 3.25);
            //dagTime.Add(4, 0, null); // if e.g.: Unreachable in P time //
            dagTime.Add(4, 0, 10.5);
            Console.WriteLine(dagTime);

            Console.WriteLine("\nShortest Path: ");
            var dagAlgo2 = new DagAlgorithms();
            dagAlgo2.ShortestPath(dagTime, 1);

            for (int i = 0; i < dagAlgo2.Shortest.Length; i++)
                Console.WriteLine("\t {0} +  -> Weights : [{1}]", i, dagAlgo2.Shortest[i]);

            Console.WriteLine("\nPredessors: ");
            for (int i = 0; i < dagAlgo2.Predecessors.Length; i++)
            {
                var pred = dagAlgo2.Predecessors[i];
                Console.WriteLine("pred[{0}] : {1}", i, pred != null ? pred.ToString() : "NULL");
            }
        }
Ejemplo n.º 42
0
        private static void Dikstra()
        {
            var directedGraph = new AdjacencyList(5);
            directedGraph.Add(1, 2, 1);
            directedGraph.Add(1, 1, 4);         // Dijkstra accepts cycles, But not negative weights //
            directedGraph.Add(2, 3, 5);
            directedGraph.Add(3, 4, 10);
            directedGraph.Add(4, 0, 2);

            var dijskra = new Dijkstra();
            dijskra.Compute(directedGraph, 1);
            for (int i = 0; i < dijskra.Shortest.Length; i++)
                Console.WriteLine("\t {0} +  -> Weights : [{1}]", i, dijskra.Shortest[i]);

            Console.WriteLine("\nPredessors: ");
            for (int i = 0; i < dijskra.Predecessors.Length; i++)
            {
                var pred = dijskra.Predecessors[i];
                Console.WriteLine("pred[{0}] : {1}", i, pred != null ? pred.ToString() : "NULL");
            }
        }
 public MatrixTraversal(AdjacencyList list, short[] clr)
 {
     Initialize(list, clr);
 }
Ejemplo n.º 44
0
 public RoadNetwork()
 {
     nodesIds = new List<long>();
     adjacentArcs = new AdjacencyList<Node>();
     mapNodeId = new Dictionary<long, Node>();
 }