Ejemplo n.º 1
1
        public static Graph<int> DijkstrasAlg(Graph<int> graph)
        {
            List<Node<int>> nodeset = graph.nodeset.ToList<Node<int>>();
            Graph<int> sptGraph = new Graph<int>();

            while (nodeset.Count > 0)
            {
                Minheapify(nodeset);
                Node<int> root = nodeset[0];
                nodeset.RemoveAt(0);
                Node<int> sptNode = new Node<int>(root.data);

                if (root.parent != null)
                {
                    sptGraph.AddEdge(sptNode, root.parent, root.key);
                    root.parent = null;
                }

                for (int i = 0; i < root.neighbors.Count; i++)
                {
                    if (root.neighbors[i].key > (root.cost[i] + root.key))
                    {
                        root.neighbors[i].key = root.cost[i] + root.key;
                        root.neighbors[i].parent = sptNode;
                    }
                }
            }

            sptGraph.printGraph();
            return sptGraph;
        }
Ejemplo n.º 2
0
        private Dictionary<string, int> st; // String -> index

        #endregion Fields

        #region Constructors

        public SymbolGraph(int count=5)
        {
            this.count = count;
            keys=new string[count];
            st = new Dictionary<string, int>();
            G=new Graph(count);
        }
 public void ReturnsGraphEdgeCounterObject()
 {
     int[,] array = { { 0, 1 }, { 1, 0 } };
     Graph graph = new Graph(array);
     GraphEdgeCounter edgeCounter = new GraphEdgeCounter(graph);
     Assert.IsNotNull(edgeCounter);
 }
Ejemplo n.º 4
0
        public GraphLayout()
        {
#if SILVERLIGHT
            this.DefaultStyleKey = typeof(GraphLayout);
#endif

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                var graph = new Graph<string, Edge<string>>();
                var a = "A";
                var b = "B";
                var c = "C";
                var d = "D";
                var e = "E";
                var f = "F";
                graph.AddVertex(a);
                graph.AddVertex(b);
                graph.AddVertex(c);
                graph.AddVertex(d);
                graph.AddVertex(e);
                graph.AddVertex(f);
                graph.AddEdge(new Edge<string>(a, b));
                graph.AddEdge(new Edge<string>(a, c));
                graph.AddEdge(new Edge<string>(a, d));
                graph.AddEdge(new Edge<string>(b, c));
                graph.AddEdge(new Edge<string>(b, d));
                graph.AddEdge(new Edge<string>(c, d));
                graph.AddEdge(new Edge<string>(e, f));
                graph.AddEdge(new Edge<string>(e, c));
                graph.AddEdge(new Edge<string>(c, f));
                this.Graph = graph;
                graph.Ratio = 0.5;
            }
        }
Ejemplo n.º 5
0
        //Time: O(E logV) using adjacency list rep (using BFS on keys)
        //Find minimum spanning tree (connected nodes with min cost edges, E = V-1)
        //1. Place the graph in min heap (using keys)
        //2. Extract the min key node and add to MST graph
        //3. Update the keys of adjacent nodes (if key > cost then update)
        //4. Minheapify the remaining nodes in the graph and repeat from step 2 until the entire list is empty
        private static Graph<int> PrimsAlg(Graph<int> graph)
        {
            Graph<int> mstGraph = new Graph<int>(); //Generate a new MST graph
            List<Node<int>> nodeset = graph.nodeset.ToList<Node<int>>();    //Create a new list of nodes from existing graph, so that we don't modify the given graph
            while (nodeset.Count > 0)
            {
                Minheapify(nodeset);    //Place the list in MinHeap
                Node<int> root = nodeset[0];    //Extract Min node
                Node<int> mstNode = new Node<int>(root.data);   //Create a new node for MST graph
                if (root.parent != null)    //Add nodes and edges between them
                {
                    mstGraph.AddEdge(mstNode, root.parent, root.key);
                    root.parent = null; //reset the parent node
                }

                nodeset.RemoveAt(0);    //Extract root node (remove from list)

                for(int i = 0; i< root.neighbors.Count; i++)
                {
                    if (root.neighbors[i].key > root.cost[i])   //Update keys of neighboring nodes if the min node
                    {
                        root.neighbors[i].key = root.cost[i];
                        root.neighbors[i].parent = mstNode;
                    }
                }
            }
            mstGraph.printGraph();
            return mstGraph;
        }
 public static double AverageEdgeWeight(int a, Graph G)
 {
     double sum = 0;
     if (a == 1)
     {
         for (int i = 0; i < G.E.Count; i++)
         {
             sum += G.E[i].Weight;
         }
         return sum / G.E.Count;
     }
     else
     {
         for (int i = 0; i < G.E.Count; i++)
         {
             if (i != longestEdgeindex)
             {
                 sum += G.E[i].Weight;
             }
         }
         return sum / (G.E.Count - 1);
     }
     /*
      Метод возвращает среднюю длину ребра графа при значении параметра, равном 1
      Метод возвращает сребнюю длину ребра без учёта самого длинного при любом другом значении параметра
      */
 }
Ejemplo n.º 7
0
 private void dfs(Graph G, int v)
 {
     marked[v-1] = true;
     count++;
     foreach (int w in G.Adj(v-1))
         if (!marked[w-1]) dfs(G, w);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Founds length of the shortest way from start to finish.
        /// If way does not exist, it returns -1
        /// </summary>
        public static int GetShortestWayLength(this Graphs.Graph graph, int start, int finish)
        {
            if (!graph.IsEdgeCorrect(start, finish))
            {
                throw new ArgumentException("Search called for invalid vertex");
            }

            int[] distances = new int[graph.VertexNumber];
            for (int i = 0; i < graph.VertexNumber; ++i)
            {
                distances[i] = -1;
            }
            distances[start] = 0;
            Queue <int> vertexToColor = new Queue <int>();

            vertexToColor.Enqueue(start);
            while (vertexToColor.Count != 0)
            {
                int vertexNow = vertexToColor.Dequeue();
                foreach (var neighbour in graph.GetNeighboursList(vertexNow))
                {
                    if (distances[neighbour] == -1 || distances[vertexNow] + 1 < distances[neighbour])
                    {
                        distances[neighbour] = distances[vertexNow] + 1;
                        vertexToColor.Enqueue(neighbour);
                    }
                }
            }
            return(distances[finish]);
        }
Ejemplo n.º 9
0
        public MainWindow()
        {
            gg = new Graph();

            number = 0;
            InitializeComponent();
        }
Ejemplo n.º 10
0
        public void ReturnsGraphObjectWhenPassingArrayToConstructor()
        {
            int[,] array = { { 0, 1 }, { 1, 0 } };
            Graph graph = new Graph(array);

            Assert.NotNull(graph);
            Assert.AreEqual(array, graph.Array);
        }
Ejemplo n.º 11
0
        public void ReturnsValidString()
        {
            int[,] array = {{0, 1}, {1, 0}};
            Graph graph = new Graph(array);

            string expectedString = "0 1\r\n1 0";
            Assert.AreEqual(expectedString, graph.ToString());
        }
Ejemplo n.º 12
0
        private bool[] marked; // Has dfs() been called for this vertex?

        #endregion Fields

        #region Constructors

        public Paths(Graph G)
        {
            marked = new bool[G.V];
            edgeTo = new List<int>[G.V];
            intEdgeTo();
            this.s = G.V;
            dfs(G, 1);
        }
Ejemplo n.º 13
0
 public DepthFirstSearch(Graph G, int s)
 {
     if (s < 1 || s > G.V)
         s = G.V;
     marked = new bool[G.V];
     dfs(G, s);
     size = G.V;
 }
        public void CountsGraphEdgesConcurrentlyMoreThanOnce()
        {
            int[,] array = { { 0, 1 }, { 1, 0 } };
            Graph graph = new Graph(array);
            GraphEdgeCounter edgeCounter = new GraphEdgeCounter(graph);

            edgeCounter.CountConcurrently();
            Assert.DoesNotThrow(() => edgeCounter.CountConcurrently());
        }
        public void CountsGraphEdgesConcurrently()
        {
            int[,] array = { { 0, 1 }, { 1, 0 } };
            Graph graph = new Graph(array);
            GraphEdgeCounter edgeCounter = new GraphEdgeCounter(graph);

            int numberOfEdges = edgeCounter.CountConcurrently();

            Assert.AreEqual(2, numberOfEdges);
        }
Ejemplo n.º 16
0
        public MainWindowViewModel()
        {
            //load dot file
            var parser = Dot.AntlrParser.AntlrParserAdapter<string>.GetParser();
            var dotFileReader = new StreamReader(@"D:\Github\LiveActive\SmartAnalyzer\Projects\callgraph.dot");
            var result = parser.Parse(dotFileReader);
               // if (result != null)
               //     this.Graph = result;

            var graph = new Graph<Person>();
            var a = new Person(graph) { Name = "Jonh", Avatar = "./Avatars/avatar1.jpg" };
            var b = new Person(graph) { Name = "Michael", Avatar = "./Avatars/avatar2.gif" };
            var c = new Person(graph) { Name = "Kenny" };
            var d = new Person(graph) { Name = "Lisa" };
            var e = new Person(graph) { Name = "Lucy", Avatar = "./Avatars/avatar3.jpg" };
            var f = new Person(graph) { Name = "Ted Mosby" };
            var g = new Person(graph) { Name = "Glen" };
            var h = new Person(graph) { Name = "Alice", Avatar = "./Avatars/avatar1.jpg" };

            graph.AddVertex(a);
            graph.AddVertex(b);
            graph.AddVertex(c);
            graph.AddVertex(d);
            graph.AddVertex(e);
            graph.AddVertex(f);

            var subGraph = new SubGraph<Person> { Label = "Work" };
            graph.AddSubGraph(subGraph);
            subGraph.AddVertex(g);
            subGraph.AddVertex(h);
            graph.AddEdge(new Edge<Person>(g, h));
            graph.AddEdge(new Edge<Person>(a, g));

            var subGraph2 = new SubGraph<Person> {Label = "School"};
            graph.AddSubGraph(subGraph2);
            var loner = new Person(graph) { Name = "Loner", Avatar = "./Avatars/avatar1.jpg" };
            subGraph2.AddVertex(loner);
            graph.AddEdge(new Edge<SubGraph<Person>>(subGraph, subGraph2) { Label = "Link between groups" } );

            graph.AddEdge(new Edge<Person>(c, d) { Label = "In love", DestinationArrowLabel = "boyfriend", SourceArrowLabel = "girlfriend" });

            graph.AddEdge(new Edge<Person>(c, g, new Arrow(), new Arrow()));
            graph.AddEdge(new Edge<Person>(c, a, new Arrow()) { Label = "Boss" });
            graph.AddEdge(new Edge<Person>(d, h, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(f, h, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(f, loner, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(f, b, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(e, g, new Arrow(), new Arrow()) { Label = "Siblings" });

            this.Graph = graph;
            this.Graph.Changed += GraphChanged;
            this.NewPersonName = "Enter new name";
            this.UpdatePersonNewName = "Enter new name";
        }
Ejemplo n.º 17
0
 private void dfs(Graph G, int v)
 {
     marked[v-1] = true;
     foreach (int w in G.Adj(v-1))
         if (!marked[w-1])
         {
             edgeTo[w - 1].Add(v);
             edgeTo[v - 1].Add(w);
             dfs(G, w);
         }
 }
Ejemplo n.º 18
0
        public MainWindowViewModel()
        {
            var graph = new Graph<Person>();
            var a = new Person();
            var b = new Person();
            var c = new Person();

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

            graph.AddEdge(new Edge<Person>(c, a));

            this.Graph = graph;
        }
Ejemplo n.º 19
0
 public Form1()
 {
     InitializeComponent();
     DoubleBuffered = true;
     this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
     G = new Graph();
     end = 0;
     Invalidate();
     clicked = false;
     formwidth = this.Size.Width;
     formheight = this.Size.Height;
     movestart = new PointF();
     moving = false;
     textBox1.Text = "2";
     ParScroll = new Form2();
 }
Ejemplo n.º 20
0
        public MainWindowViewModel()
        {
            var graph = new Graph<Person>();
            var a = new Person(graph) { Name = "Jonh", Avatar = "./Avatars/avatar1.jpg" };
            var b = new Person(graph) { Name = "Michael", Avatar = "./Avatars/avatar2.gif" };
            var c = new Person(graph) { Name = "Kenny" };
            var d = new Person(graph) { Name = "Lisa" };
            var e = new Person(graph) { Name = "Lucy", Avatar = "./Avatars/avatar3.jpg" };
            var f = new Person(graph) { Name = "Ted Mosby" };
            var g = new Person(graph) { Name = "Glen" };
            var h = new Person(graph) { Name = "Alice", Avatar = "./Avatars/avatar1.jpg" };

            graph.AddVertex(a);
            graph.AddVertex(b);
            graph.AddVertex(c);
            graph.AddVertex(d);
            graph.AddVertex(e);
            graph.AddVertex(f);

            var subGraph = new SubGraph<Person> { Label = "Work" };
            graph.AddSubGraph(subGraph);
            subGraph.AddVertex(g);
            subGraph.AddVertex(h);
            graph.AddEdge(new Edge<Person>(g, h));
            graph.AddEdge(new Edge<Person>(a, g));

            var subGraph2 = new SubGraph<Person> {Label = "School"};
            graph.AddSubGraph(subGraph2);
            var loner = new Person(graph) { Name = "Loner", Avatar = "./Avatars/avatar1.jpg" };
            subGraph2.AddVertex(loner);
            graph.AddEdge(new Edge<SubGraph<Person>>(subGraph, subGraph2) { Label = "Link between groups" } );

            graph.AddEdge(new Edge<Person>(c, d) { Label = "In love", DestinationArrowLabel = "boyfriend", SourceArrowLabel = "girlfriend" });

            graph.AddEdge(new Edge<Person>(c, g, new Arrow(), new Arrow()));
            graph.AddEdge(new Edge<Person>(c, a, new Arrow()) { Label = "Boss" });
            graph.AddEdge(new Edge<Person>(d, h, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(f, h, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(f, loner, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(f, b, new DiamondArrow(), new DiamondArrow()));
            graph.AddEdge(new Edge<Person>(e, g, new Arrow(), new Arrow()) { Label = "Siblings" });

            this.Graph = graph;
            this.Graph.Changed += GraphChanged;
            this.NewPersonName = "Enter new name";
            this.UpdatePersonNewName = "Enter new name";
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            //Read the graph details
            // it will be line sepearted with each edge represented in a line
            string filePath = @"C:\Users\raghuvg\Documents\dharma\Graphs\Graphs\Data\InputGraph.txt";

            Graph graph = new Graph(filePath);

            //Print Number of Vertices
            Console.WriteLine(" Number of Nodes  {0}" , graph.Vertices);

            //Print Edges
            Console.WriteLine("Number of Edges .. {0}", graph.Edges);

            //Print Graph
            graph.PrintGraph();

            //DFS
            graph.DFS();

            Console.ReadLine();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Reads size, amount of edges and edges list
        /// </summary>
        static Graph AskGraphFromConsole()
        {
            Console.WriteLine("Type graph size (amount of vertexes):");
            int graphSize = int.Parse(Console.ReadLine());
            var graph     = new Graphs.Graph(graphSize);

            Console.WriteLine("Type amount of edges:");
            int edgesAmount = int.Parse(Console.ReadLine());

            for (int i = 0; i < edgesAmount; ++i)
            {
                Console.WriteLine("Type edge (just pair of numbers):");
                string[] edgeInput = Console.ReadLine().Split(' ');
                if (edgeInput.Length < 2)
                {
                    throw new Exception("Bad input");
                }
                int begin = int.Parse(edgeInput[0]);
                int end   = int.Parse(edgeInput[1]);
                graph.AddEdge(begin, end);
            }
            return(graph);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            int numberOfVertices;
            Console.WriteLine("Enter the number of vertices: ");
            numberOfVertices = int.Parse(Console.ReadLine());

            GraphArrayGenerator generator = new GraphArrayGenerator();
            Graph graph = new Graph(generator.GenerateConcurrently(numberOfVertices));
            if (numberOfVertices < 16)
                Console.WriteLine("Graph\n{0}\n", graph.ToString());

            GraphEdgeCounter counter = new GraphEdgeCounter(graph);
            Stopwatch watch = new Stopwatch();
            watch.Start();
            int numberOfEdges = counter.Count();
            watch.Stop();
            Console.WriteLine("Number of edges: {0}\nTime(ms): {1}\n\n", numberOfEdges, watch.ElapsedMilliseconds);

            watch.Restart();
            numberOfEdges = counter.CountConcurrently();
            watch.Stop();
            Console.WriteLine("Multi-threaded\nNumber of edges: {0}\nTime(ms): {1}", numberOfEdges, watch.ElapsedMilliseconds);
            Console.Read();
        }
Ejemplo n.º 24
0
        public static string ToTikz(Graph graph)
        {
            var scale = 10.0;

            var noLabels = graph.Vertices.All(v => string.IsNullOrEmpty(v.Label));

            var sb = new StringBuilder();

            sb.AppendLine("\\begin{tikzpicture}[scale = " + scale + "]");
            sb.AppendLine(@"\tikzstyle{VertexStyle} = []");
            sb.AppendLine(@"\tikzstyle{EdgeStyle} = []");
            sb.AppendLine(string.Format(@"\tikzstyle{{labeledStyle}}=[shape = circle, minimum size = 6pt, inner sep = 1.2pt, draw]"));
            sb.AppendLine(string.Format(@"\tikzstyle{{unlabeledStyle}}=[shape = circle, minimum size = 6pt, inner sep = 1.2pt, draw, fill]"));

            var vertexStyleLookup = new Dictionary <string, string>();
            var edgeStyleLookup   = new Dictionary <string, string>();

            var vertexStyles = graph.Vertices.Where(v => !string.IsNullOrWhiteSpace(v.Style)).Select(v => v.Style.Trim()).Distinct().ToList();
            var edgeStyles   = graph.Edges.Where(e => !string.IsNullOrWhiteSpace(e.Style)).Select(e => e.Style.Trim()).Distinct().ToList();

            foreach (var style in vertexStyles)
            {
                string id = style;
                if (!style.StartsWith("_"))
                {
                    id = Guid.NewGuid().ToString().ToLower();
                    var s = @"\tikzstyle{" + id + @"}=[";
                    if (!style.Contains("shape"))
                    {
                        s += "shape = circle,";
                    }
                    if (!style.Contains("minimum size"))
                    {
                        s += "minimum size = 6pt,";
                    }
                    if (!style.Contains("inner sep"))
                    {
                        s += "inner sep = 1.2pt,";
                    }

                    s += "draw,";
                    s += style;
                    s  = s.TrimEnd(',') + "]";

                    sb.AppendLine(s);
                }

                vertexStyleLookup[style] = id;
            }

            foreach (var style in edgeStyles)
            {
                string id = style;
                if (!style.StartsWith("_"))
                {
                    id = Guid.NewGuid().ToString().ToLower();
                    var s = @"\tikzstyle{" + id + @"}=[";
                    s += style;
                    s  = s.TrimEnd(',') + "]";

                    sb.AppendLine(s);
                }

                edgeStyleLookup[style] = id;
            }

            var vertexNameMap = new Dictionary <Vertex, string>();

            int vertexCount = 0;

            foreach (var v in graph.Vertices)
            {
                string vertexName = "v" + vertexCount;

                vertexNameMap[v] = vertexName;

                double x = v.X;
                double y = 1.0 - v.Y;

                if (string.IsNullOrEmpty(v.Style))
                {
                    sb.AppendLine(string.Format(@"\Vertex[style = {4}, x = {0:0.000}, y = {1:0.000}, L = \tiny {{{2}}}]{{{3}}}", x, y, Mathify(v.Label), vertexName, string.IsNullOrEmpty(v.Label) ? "unlabeledStyle" : "labeledStyle"));
                }
                else
                {
                    sb.AppendLine(string.Format(@"\Vertex[style = {4}, x = {0:0.000}, y = {1:0.000}, L = \tiny {{{2}}}]{{{3}}}", x, y, Mathify(v.Label), vertexName, vertexStyleLookup[v.Style.Trim()]));
                }

                vertexCount++;
            }

            foreach (var e in graph.Edges)
            {
                if (string.IsNullOrEmpty(e.Style))
                {
                    sb.AppendLine(string.Format(@"\Edge[label = \tiny {{{2}}}, labelstyle={{auto=right, fill=none}}]({0})({1})", vertexNameMap[e.V1], vertexNameMap[e.V2], Mathify(e.Label)));
                }
                else
                {
                    sb.AppendLine(string.Format(@"\Edge[style = {2}, label = \tiny {{{3}}}, labelstyle={{auto=right, fill=none}}]({0})({1})", vertexNameMap[e.V1], vertexNameMap[e.V2], edgeStyleLookup[e.Style.Trim()], Mathify(e.Label)));
                }
            }

            sb.AppendLine(@"\end{tikzpicture}");

            return(sb.ToString());
        }
 public Person(Graph<Person> graph)
 {
     this.graph = graph;
     this.Avatar = "./Avatars/avatarAnon.gif";
 }
Ejemplo n.º 26
0
        static void Main()
        {
            var reader = new StreamReader("../../input/2.txt");
            Console.SetIn(reader);

            var firstInputLineParams = Console.ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => int.Parse(x))
                .ToArray();

            var numberOfBuildings = firstInputLineParams[0];
            var numberOfStreets = firstInputLineParams[1];
            var numberOfHospitals = firstInputLineParams[2];

            var hospitals = new HashSet<int>();
            var readHospitals = Console.ReadLine()
            .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(x => int.Parse(x));

            foreach (var h in readHospitals)
            {
                hospitals.Add(h);
            }

            var graph = new Graph<int>();
            var connections = new List<int[]>();

            for (int i = 0; i < numberOfStreets; i++)
            {
                connections.Add(Console.ReadLine()
                    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => int.Parse(x))
                    .ToArray());
            }

            // AddNodesToGraph
            foreach (var connection in connections)
            {
                var fromNode = connection[0];
                var toNode = connection[1];
                var distance = connection[2];

                if (!graph.ContainsNode(fromNode))
                {
                    graph.AddNode(fromNode);
                }

                if (!graph.ContainsNode(toNode))
                {
                    graph.AddNode(toNode);
                }

                graph.AddConnection(fromNode, toNode, distance, true);
            }

            var distanceCalc = new DistanceCalculator<int>();

            var minDist = int.MaxValue;
            foreach (var hospital in hospitals)
            {
                var dist = distanceCalc.CalculateDistances(graph, hospital)
                    .Where(x => !hospitals.Contains(x.Key))
                    .Sum(x => x.Value);

                if (minDist > dist)
                {
                    minDist = dist;
                }
            }

            Console.WriteLine(minDist);
        }
Ejemplo n.º 27
0
 private void button2_Click(object sender, EventArgs e)
 {
     G = new Graph();
     end = 0;
     Invalidate();
 }
 public static void ClusterSelection(double k, Graph G , int n)
 {
     for (int i = 0; i < G.V.Count; i++)
     {
         for (int j = i + 1; j < G.V.Count; j++)
         {
             G.E.Add(new Edge(G.V[i], G.V[j]));
         }
     }
         G.FindMinSpanTree(G.V[0]);
     for (int i = 0; i < G.E.Count; i++)
     {
         if (!G.E[i].optimal)
         {
             G.E.Remove(G.E[i]);
             i--;
         }
     }
     for (int i = 0; i < G.E.Count(); i++)
     {
         Form1.el += Convert.ToString(Math.Round(G.E[i].Weight, 2));
         Form1.el += "; ";
     }
     Form1.al = Convert.ToString(AverageEdgeWeight(1, G));
     LongestEdge(G);
     r =  RelCount(G);
     if (n == 1)
     {
         while (lEdgeWeight > k * slEdgeWeight)
         {
             G.E.Remove(G.E[longestEdgeindex]);
             LongestEdge(G);
         }
     }
     else
     {
         if (n == 2)
         {
             while (lEdgeWeight > k * AverageEdgeWeight(1, G))
             {
                 G.E.Remove(G.E[longestEdgeindex]);
                 LongestEdge(G);
             }
         }
         else
         {
             if (n == 3)
             {
                 double temp = AverageEdgeWeight(1, G);
                 while (lEdgeWeight > k * temp)
                 {
                     G.E.Remove(G.E[longestEdgeindex]);
                     LongestEdge(G);
                 }
             }
             else
             {
                 while (lEdgeWeight > k * AverageEdgeWeight(2, G))
                 {
                     G.E.Remove(G.E[longestEdgeindex]);
                     LongestEdge(G);
                 }
             }
         }
     }
 }
Ejemplo n.º 29
0
        public static void Main(string[] args)
        {
            /*Graph<int> graph = new Graph<int>(10);
             * graph.AddVertex(1);
             * graph.AddVertex(11);
             * graph.AddVertex(13);
             * graph.AddVertex(90);
             * graph.AddVertex(-1);
             * graph.AddEdge(0, 1); // 1-2
             * graph.AddEdge(1, 4); // 2-5
             * graph.AddEdge(4, 2); // 5-3
             * graph.AddEdge(2, 3); // 3-4
             * Console.WriteLine("DFS of {0}", graph);
             * graph.DFS(0);
             * Console.WriteLine("BFS of {0}", graph);
             * graph.BFS(0);
             *
             * Graph<String> strGraph = new Graph<string>(6);
             * strGraph.AddVertex("a");
             * strGraph.AddVertex("b");
             * strGraph.AddVertex("c");
             * strGraph.AddVertex("d");
             * strGraph.AddVertex("e");
             * strGraph.AddEdge(0, 1); // 1-2
             * strGraph.AddEdge(1, 4); // 2-5
             * strGraph.AddEdge(4, 2); // 5-3
             * strGraph.AddEdge(2, 3); // 3-4
             * Console.WriteLine("{0} DFS", strGraph);
             * strGraph.DFS(0);*/

            /*Graph<int> g3 = new Graph<int>(5);
             * g3.AddVertex(0); //0
             * g3.AddVertex(1); //1
             * g3.AddVertex(2); //2
             * g3.AddVertex(3); //3
             *
             * g3.AddEdge(0, 1, false);
             *
             * g3.AddEdge(0, 2, false);
             *
             * g3.AddEdge(1, 2, false);
             *
             * g3.AddEdge(2, 3, false);
             *
             * g3.AddEdge(3, 3, false);
             *
             * Console.WriteLine("g3 BFS");
             * g3.BFS(2); // c a b d*/

            /*Graph<char> g4 = new Graph<char>(5);
             * g4.AddVertex('a'); //0
             * g4.AddVertex('b'); //1
             * g4.AddVertex('c'); //2
             * g4.AddVertex('d'); //3
             * g4.AddEdge(0, 1, false);
             *
             * g4.AddEdge(0, 2, false);
             *
             * g4.AddEdge(1, 2, false);
             *
             * g4.AddEdge(2, 3, false);
             *
             * g4.AddEdge(3, 3, false);
             * Console.WriteLine("g4 BFS");
             * g4.BFS(2); */

            Graph <char> g5 = new Graph <char>(6);

            g5.AddVertex('a'); //0
            g5.AddVertex('b'); //1
            g5.AddVertex('c'); //2
            g5.AddVertex('d'); //3
            g5.AddVertex('e'); //4
            g5.AddVertex('f'); //5

            g5.AddEdge(0, 1, 2, false);
            g5.AddEdge(1, -0, 2, false);

            g5.AddEdge(0, 2, 5, false);
            g5.AddEdge(2, 0, 5, false);


            g5.AddEdge(1, 2, 9, false);
            g5.AddEdge(2, 1, 9, false);

            g5.AddEdge(2, 3, 3, false);
            g5.AddEdge(3, 2, 3, false);


            g5.AddEdge(3, 4, 2, false);
            g5.AddEdge(4, 3, 2, false);

            g5.AddEdge(4, 5, 3, false);
            g5.AddEdge(5, 4, 3, false);

            g5.AddEdge(0, 4, 4, false);
            g5.AddEdge(4, 0, 4, false);

            g5.AddEdge(0, 5, 10, false);
            g5.AddEdge(5, 0, 10, false);

            //Console.WriteLine("g5 Dijkstra");
            //g5.Dijkstra(1);
            g5.PrimMST();
        }
 public static double RelCount(Graph G)
 {
     return lEdgeWeight / AverageEdgeWeight(1, G);
 }
Ejemplo n.º 31
0
        // Открыть граф из файла
        private void button7_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (Ellipse el in gg.getelipse.Values) {
                    canva.Children.Remove(el);
                }
                foreach (TextBlock tx in gg.textes.Values)
                {
                    canva.Children.Remove(tx);
                }
                foreach (ArrowLine ln in gg.ArrowLines.Keys)
                {
                    canva.Children.Remove(ln);
                }
                gg.direction.Clear();

                gg = new Graph();

                    string Content = System.IO.File.ReadAllText(openFileDialog1.FileName);
                    string[] integersString = Content.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    int[] integers = new int[integersString.Length];
                    int current = 0;
                    foreach(string s in integersString){
                        integers[current++] = int.Parse(s);
                    }
                    //System.IO.StreamReader reader = new System.IO.StreamReader(openFileDialog1.FileName);
                    current = 0;

                    number = integers[current++];

                    for (int i = 0; i < number; i++)
                    {
                        Ellipse el = new Ellipse();

                        int index = integers[current++];
                        int x = integers[current++];
                        int y = integers[current++];
                        gg.nodes.Add(el, index);
                        gg.getelipse.Add(index, el);

                        el.MouseDown += new MouseButtonEventHandler(ellipse_MouseDown);
                        el.Width = 30;
                        el.Height = 30;
                        el.StrokeThickness = 1;
                        el.Stroke = Brushes.Black;
                        el.Fill = Brushes.Blue;

                        canva.Children.Add(el);
                        Canvas.SetLeft(el, x);
                        Canvas.SetTop(el, y);
                    }

                    for (int i = 0; i < number; i++) {
                        gg.graph.Add(new List<int>());
                        for (int j = 0; j < number; j++)
                        {
                            int w = integers[current++];

                            gg.graph[i].Add(w);

                            if (w != 0)
                            {

                                ArrowLine ln = new ArrowLine();

                                ln.StrokeThickness = 2;
                                ln.Stroke = Brushes.Black;
                                ln.Fill = Brushes.Blue;
                                ln.X1 = Canvas.GetLeft(gg.getelipse[i]) + 15;
                                ln.Y1 = Canvas.GetTop(gg.getelipse[i]) + 15;
                                ln.X2 = Canvas.GetLeft(gg.getelipse[j]) + 15;
                                ln.Y2 = Canvas.GetTop(gg.getelipse[j]) + 15;

                                canva.Children.Add(ln);
                                gg.ArrowLines.Add(ln, Tuple.Create(i, j));
                                gg.edges.Add(Tuple.Create(i, j), ln);
                                gg.direction.Add(Tuple.Create(ln, gg.getelipse[i]), 1);
                                gg.direction.Add(Tuple.Create(ln, gg.getelipse[j]), 2);
                                Text(ln, (ln.X1 + ln.X2) / 2, (ln.Y1 + ln.Y2) / 2, w.ToString(), Colors.Black);
                            }

                        }
                    }

            }
        }
 public static void LongestEdge(Graph G)
 {
     if (G.E.Count > 1)
     {
         longestEdgeindex = 0;
         lEdgeWeight = G.E[0].Weight;
         for (int i = 0; i < G.E.Count; i++)
         {
             if (G.E[i].Weight > lEdgeWeight)
             {
                 slEdgeWeight = lEdgeWeight;
                 slongestEdgeindex = longestEdgeindex;
                 lEdgeWeight = G.E[i].Weight;
                 longestEdgeindex = i;
             }
         }
         for (int i = 0; i < G.E.Count; i++)
         {
             if (i != longestEdgeindex)
             {
                 if (G.E[i].Weight > slEdgeWeight && G.E[i].Weight != lEdgeWeight)
                 {
                     slEdgeWeight = G.E[i].Weight;
                     slongestEdgeindex = i;
                 }
             }
         }
     }
 }
Ejemplo n.º 33
0
        public static void DoTiling(Graphs.Graph g, List <Vector> p, List <int> set)
        {
            if (g.Edges.Count <= 0)
            {
                return;
            }

            var r = new Vector(g.Edges[0].V1.X, g.Edges[0].V1.Y).Distance(new Vector(g.Edges[0].V2.X, g.Edges[0].V2.Y));

            var edgesToAdd = new List <Tuple <int, int> >();

            for (int i = 0; i < set.Count; i++)
            {
                g.Vertices[set[i]].Padding = 0.02f;
                g.Vertices[set[i]].Style   = "_RedDotStyle";

                for (int j = i + 1; j < set.Count; j++)
                {
                    if (p[set[i]].Distance(p[set[j]]) < 3 * r - MinDelta)
                    {
                        edgesToAdd.Add(new Tuple <int, int>(set[i], set[j]));
                    }
                }
            }

            foreach (var e in edgesToAdd)
            {
                var vs = new List <int>()
                {
                    e.Item1, e.Item2
                };
                var nonIncident = edgesToAdd.Where(ea => !vs.Contains(ea.Item1) && !vs.Contains(ea.Item2)).ToList();

                if (nonIncident.Any(ea => SegmentsIntersect(g.Vertices[e.Item1], g.Vertices[e.Item2], g.Vertices[ea.Item1], g.Vertices[ea.Item2])))
                {
                    continue;
                }

                var between = g.Vertices.Where(v => OnLineSegment(g.Vertices[e.Item1], g.Vertices[e.Item2], v)).Where(v => v != g.Vertices[e.Item1] && v != g.Vertices[e.Item2]).ToList();

                var thickness = 6;
                if (between.Count == 0)
                {
                    g.AddEdge(g.Vertices[e.Item1], g.Vertices[e.Item2], Edge.Orientations.None, 1, thickness, "_GreenEdgeStyle");
                }
                else
                {
                    for (int i = 0; i < between.Count; i++)
                    {
                        var ee = g.GetEdge(between[i], g.Vertices[e.Item1]);
                        if (ee != null)
                        {
                            ee.Style     = "_GreenEdgeStyle";
                            ee.Thickness = thickness;
                        }

                        ee = g.GetEdge(between[i], g.Vertices[e.Item2]);
                        if (ee != null)
                        {
                            ee.Thickness = thickness;
                            ee.Style     = "_GreenEdgeStyle";
                        }
                    }
                }
            }
        }
Ejemplo n.º 34
0
        public static Graphs.Graph BuildSerendipitousEdgeGraph(AlgorithmBlob blob, List <Vector> p, List <List <int> > diamonds, out Graphs.Graph rotatedGraph)
        {
            var dim         = GraphicsLayer.ARGB.FromFractional(0.5, 0.5, 0.5, 0.5);
            var transparent = GraphicsLayer.ARGB.FromFractional(0.0, 0.5, 0.5, 0.5);

            var vertices = new List <Vertex>();

            for (int i = 0; i < diamonds.Count; i++)
            {
                var v = new Vertex(diamonds[i].Select(t => p[t].X).Average(), diamonds[i].Select(t => p[t].Y).Average());
                v.Label = Enum.GetName(typeof(DiamondType), ClassifyDiamond(p, diamonds[i]));
                vertices.Add(v);
            }

            var rotatedDiamonds = diamonds.Select(d => RotateCoordinates(p, d)).ToList();
            var edges           = new List <Edge>();

            var r = p[diamonds[0][0]].Distance(p[diamonds[0][2]]);

            var rotatedVertices = new List <Vertex>();
            var rotatedEdges    = new List <Edge>();

            var rotatedVertexLookup = new Vertex[diamonds.Count, 4];

            for (int a = 0; a < diamonds.Count; a++)
            {
                for (int i = 0; i < 4; i++)
                {
                    var v = new Vertex(rotatedDiamonds[a][i].X, rotatedDiamonds[a][i].Y);
                    if (i == 0)
                    {
                        v.Padding = 0.02f;
                    }

                    rotatedVertices.Add(v);
                    rotatedVertexLookup[a, i] = v;
                }

                var originals = new Vertex[4];
                for (int i = 1; i < 4; i++)
                {
                    var v = new Vertex(p[diamonds[a][i]].X, p[diamonds[a][i]].Y);
                    v.Color   = transparent;
                    v.Padding = 0.02f;

                    rotatedVertices.Add(v);
                    originals[i] = v;
                }

                rotatedEdges.Add(new Edge(originals[2], originals[3])
                {
                    Color = dim
                });
                rotatedEdges.Add(new Edge(originals[1], originals[2])
                {
                    Color = dim
                });
                rotatedEdges.Add(new Edge(originals[1], originals[3])
                {
                    Color = dim
                });

                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 0], originals[2])
                {
                    Color = dim
                });
                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 0], originals[3])
                {
                    Color = dim
                });

                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 0], rotatedVertexLookup[a, 2]));
                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 0], rotatedVertexLookup[a, 3]));
                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 1], rotatedVertexLookup[a, 2]));
                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 1], rotatedVertexLookup[a, 3]));
                rotatedEdges.Add(new Edge(rotatedVertexLookup[a, 2], rotatedVertexLookup[a, 3]));
                rotatedEdges.Add(new Edge(originals[1], rotatedVertexLookup[a, 1]));
            }


            for (int a = 0; a < diamonds.Count; a++)
            {
                for (int b = a + 1; b < diamonds.Count; b++)
                {
                    if (ClassifyDiamond(p, diamonds[a]) == ClassifyDiamond(p, diamonds[b]))
                    {
                        continue;
                    }

                    for (int i = 1; i < 4; i++)
                    {
                        for (int j = 1; j < 4; j++)
                        {
                            var distance = rotatedDiamonds[a][i].Distance(rotatedDiamonds[b][j]);
                            var offset   = Math.Abs(distance - r);
                            if (offset < MinDelta)
                            {
                                var e = new Edge(vertices[a], vertices[b]);
                                e.Thickness = 6;
                                edges.Add(e);

                                var ee = new Edge(rotatedVertexLookup[a, i], rotatedVertexLookup[b, j]);
                                ee.Thickness = 6;
                                rotatedEdges.Add(ee);
                            }
                        }
                    }
                }
            }

            rotatedGraph = new Graphs.Graph(rotatedVertices, rotatedEdges);
            return(new Graphs.Graph(vertices, edges));
        }
Ejemplo n.º 35
0
 public GraphEdgeCounter(Graph graph)
 {
     if (graph == null)
         throw new ArgumentNullException();
     this.graph = graph;
 }
Ejemplo n.º 36
0
        public KruscalAlgorithm(Graph Graph)
        {
            MinimumSpanningTree = new List <Edge>();

            InnerGraph = (Graph)Graph.Clone();
        }