Static class containing graph algorithms.
Example #1
0
        public static void Main1(string[] arg)
        {
            Graph.Graph graph = new Graph.Graph("g.txt");
            CC          cc    = new CC(graph);

            string s = "";

            foreach (var item in cc.visited)
            {
                s += item.ToString();
            }
            Console.WriteLine(s);

            Console.WriteLine(cc.CCCount);

            Console.WriteLine(cc.isConnected(0, 6));
            Console.WriteLine(cc.isConnected(0, 5));

            var com = cc.components();

            for (int i = 0; i < com.Length; i++)
            {
                Console.Write(i + "   :   ");
                for (int j = 0; j < com[i].Count; j++)
                {
                    Console.Write($" {com[i][j]},");
                }
                Console.Write("\n");
            }
        }
Example #2
0
        public static void Main1(string[] arg)
        {
            Graph.Graph    graph = new Graph.Graph("g.txt");
            CycleDetection cd    = new CycleDetection(graph);

            Console.WriteLine(cd.isCycle);
        }
Example #3
0
        private static void DFS(Graph g)
        {
            DFS dfs = new DFS(g, 0);
            for (int i = 0; i < g.Vertices; i++)
            {
                if (dfs.Marked(i))
                {
                    Console.Write(i + " ");
                }
            }
            Console.WriteLine();

            if (dfs.Count == g.Vertices)
                Console.WriteLine("Connected");
            else
                Console.WriteLine("Not Connected");

            IEnumerable<int> path = dfs.Path(3);

            if (path != null)
            {
                path.ToList().ForEach(x => Console.Write(x + " "));
            }
            Console.WriteLine();
        }
Example #4
0
        public BinaryGraph(Graph.Graph g)
        {
            this.G  = g;
            visited = new int[g.V];
            for (int i = 0; i < g.V; i++)
            {
                visited[i] = 0;
            }
            for (int i = 0; i < g.V; i++)
            {
                if (visited[i] == 0)
                {
                    if (!DFS(i, 1))
                    {
                        isBinary = false;
                        break;
                    }
                }
            }

            foreach (var item in visited)
            {
                Console.WriteLine(item);
            }
        }
Example #5
0
        /// <summary>
        /// Method for calculating forces applied to passed <see cref="Graph"/>.
        /// Method iterates 10 times for faster results.
        /// </summary>
        /// <param name="graph">Object on which all calculations are based.</param>
        public void CalculateForces(Graph.Graph graph)
        {
            this.graph = graph;

            float area = (float)mainCanvas.ActualWidth * (float)mainCanvas.ActualHeight * 0.6f;

            factor = (float)Math.Sqrt(area / graph.NodesCount);

            for (int n = 0; n < 10; n++)
            {
                foreach (Node currentNode in graph.Nodes)
                {
                    RepulsiveDisplacement(currentNode);
                }

                foreach (Edge currentEdge in graph.Edges)
                {
                    AttractiveDisplacement(currentEdge);
                }

                foreach (Node currentNode in graph.Nodes)
                {
                    DisplaceNode(currentNode);
                }
            }
        }
Example #6
0
        public static HashSet <HashSet <int> > Run(Graph.Graph graph)
        {
            // Initial conditions
            var adjacency         = graph.CreateAdjacencyMatrix();
            var invertedAdjacency = adjacency.Fill(1) - adjacency;
            var cover             = IntializeCover(invertedAdjacency); // C
            var subCover          = new HashSet <SubMatrix>();         // X

            while (true)
            {
                var nextCover = Iteration(cover, subCover);

                if (nextCover.SetEquals(cover))
                {
                    break;
                }

                cover    = nextCover;
                subCover = CalculateSubCover(nextCover);
            }

            var stableSets = ExtractStableSets(cover);
            var result     = ExtractResult(stableSets);

            return(result);
        }
Example #7
0
        public static void Main(string[] arg)
        {
            Graph.Graph graph = new Graph.Graph("g.txt");
            BinaryGraph bg    = new BinaryGraph(graph);

            Console.WriteLine(bg.isBinary);
        }
Example #8
0
 public BFS(Graph g, int vertex)
 {
     source = vertex;
     marked = new bool[g.Vertices];
     edgeTo = new int[g.Vertices];
     Search(g, vertex);
 }
Example #9
0
 public DFS(Graph g, int sourceVertex)
 {
     marked = new bool[g.Vertices];
     edgeTo = new int[g.Vertices];
     source = sourceVertex;
     Search(g, sourceVertex);
 }
Example #10
0
        static void Main(string[] args)
        {
            Graph.Graph g = new Graph.Graph("/home/jconda/RiderProjects/graph/Test data/input1");

            Graph.Graph g1 = new Graph.Graph(g);

            Graph.Graph g2 = new Graph.Graph("/home/jconda/RiderProjects/graph/Test data/input2");

            Graph.Graph g3 = new Graph.Graph("/home/jconda/RiderProjects/graph/Test data/input3");

            Graph.Graph g4 = new Graph.Graph("/home/jconda/RiderProjects/graph/Test data/input4");

            Graph.Graph g5 = new Graph.Graph("/home/jconda/RiderProjects/graph/Test data/input5");

            Graph.Graph g6 = new Graph.Graph("/home/jconda/RiderProjects/graph/Test data/input6");

            g.CreateGraphVizFile("/home/jconda/RiderProjects/graph/Test data/output.txt");

            List <Graph.Graph> graphs = new List <Graph.Graph>();

            graphs.Add(g);
            graphs.Add(g2);
            graphs.Add(g3);
            graphs.Add(g4);
            graphs.Add(g5);
            graphs.Add(g6);

            UI ui = new UI(graphs);

            ui.MainMenu();
        }
 public OnePointCrossoverStrategy(Graph graph)
 {
     if (graph == null)
         throw new ArgumentNullException(nameof(graph));
     if (!graph.IsValid())
         throw new ArgumentException("Graph is invalid!");
     _graph = graph;
     RandomizeCrossoverPoint();
 }
Example #12
0
 public void CreateDistances(Graph.Graph <MapLocation> graph)
 {
     foreach (var edge in graph.Edges)
     {
         var position = Camera.main.WorldToScreenPoint(Vector3.Lerp(edge.Origin.Item.transform.position, edge.Destination.Item.transform.position, 0.5f));
         var text     = Instantiate(TextPrefab, position, CurrentCanvas.transform.rotation, Container.transform);
         text.GetComponent <DynamicText>().UpdateText(edge.Weight.ToString("0.00"));
     }
 }
 public static MinimumVertexCover AsDomainModel(this MinimumVertexCoverEntity entity, Graph graph = null)
 {
     var problem = new MinimumVertexCover(entity.Id);
     problem.Initialize(graph ?? entity.Graph.AsDomainModel());
     problem.SetNewSolution(problem.Graph
         .BinarySolutionAsNodes(entity.CurrentSolution
             .Select(Convert.ToBoolean).ToArray()));
     return problem;
 }
Example #14
0
        public static void  Main1(string[] arg)
        {
            Graph.Graph graph    = new Graph.Graph("g.txt");
            GraphBFS    graphBFS = new GraphBFS(graph);

            foreach (var item in graphBFS.GetOrder())
            {
                Console.WriteLine(item);
            }
        }
Example #15
0
		public GraphForm()
		{
			InitializeComponent();

			this.graph = new Graph();
			this.graph.Location = new System.Drawing.Point(0, 0);
			this.graph.Size = this.ClientSize;
			this.graph.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
			this.graph.AutoScale();

			this.Controls.Add(this.graph);
		}
Example #16
0
        public static void Main1(string[] arg)
        {
            Graph.Graph      graph            = new Graph.Graph("g.txt");
            SingleSourcePath singleSourcePath = new SingleSourcePath(graph, 0);
            var ls = singleSourcePath.path(6);

            Console.WriteLine("0-->6");
            for (int i = 0; i < ls.Count; i++)
            {
                Console.WriteLine(ls[i]);
            }
        }
Example #17
0
 public GraphDFS(Graph.Graph g)
 {
     this.G  = g;
     visited = new bool[g.V];
     for (int i = 0; i < g.V; i++)
     {
         if (!visited[i])
         {
             DFS(i);
         }
     }
 }
Example #18
0
        public static void Main1(string[] arg)
        {
            Graph.Graph graph = new Graph.Graph("g.txt");
            Path        p     = new Path(graph, 0, 6);
            var         ls    = p.path();

            Console.WriteLine("0-->6");
            for (int i = 0; i < ls.Count; i++)
            {
                Console.WriteLine(ls[i]);
            }
        }
Example #19
0
		public GraphForm2()
		{
			InitializeComponent();

			this.graphL = new Graph();
			this.graphR = new Graph();

			this.ResizeGraph();
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																																	this.graphL,
																																	this.graphR});
		}
 /// <summary>
 /// Creates SimulatedAnnealing algorithm instance
 /// </summary>
 /// <param name="graph">Graph on which algorithm will operate</param>
 /// <param name="problem">Problem for which algorithm will attempt to find solution</param>
 /// <param name="setup">Setup for algorithm's cooling process</param>
 //TODO: Introduce SavedState complex type
 public SimulatedAnnealing(Graph graph, IProblem problem, CoolingSetup setup, double? currentTemperature = null, Guid? id = null) : base(graph, problem, id)
 {
     if (setup == null)
         throw new ArgumentNullException(nameof(setup));
     if (!setup.IsValid())
         throw new ArgumentException("Setup is invalid", nameof(setup));
     CoolingSetup = setup;
     if (currentTemperature.HasValue)
         CurrentTemperature = currentTemperature.Value;
     else
         CurrentTemperature = setup.InitialTemperature;
 }
Example #21
0
 private int[] pre;//遍历时的先导
 public SingleSourcePath(Graph.Graph g, int s)
 {
     this.S = s;
     this.G = g;
     G.ValidateVertex(s);
     pre = new int[G.V];
     for (int i = 0; i < G.V; i++)
     {
         pre[i] = -1;
     }
     DFS(this.S, s);
 }
Example #22
0
 protected Algorithm(Graph graph, IProblem problem, Guid? id) : base(id)
 {
     if (problem == null)
         throw new ArgumentNullException(nameof(problem));
     if (graph == null)
         throw new ArgumentNullException(nameof(graph));
     if (!graph.IsValid())
         throw new ArgumentException("Graph is invalid", nameof(graph));
     Graph = graph;
     Problem = problem;
     problem.Initialize(graph);
 }
Example #23
0
 public GraphBFS(Graph.Graph G)
 {
     this.G  = G;
     visited = new bool[G.V];
     order   = new List <int>();
     for (int i = 0; i < G.V; i++)
     {
         if (!visited[i])
         {
             BFS(i);
         }
     }
 }
Example #24
0
        static void Main(string[] args)
        {
            Graph.Graph g = new Graph.Graph();

            g.addNode("a");
            g.addNode("b");
            g.addNode("c");
            g.addNode("d");
            g.addNode("e");
            g.addNode("f");
            g.addNode("g");
            g.addNode("h");


            g.addDirectedVertex("a", "b", -1);
            g.addDirectedVertex("a", "c", 4);
            g.addDirectedVertex("b", "c", 3);
            g.addDirectedVertex("b", "e", 3);
            g.addDirectedVertex("b", "d", 2);
            g.addDirectedVertex("d", "b", 1);
            g.addDirectedVertex("e", "d", -3);
            g.addDirectedVertex("d", "c", 5);

            //Console.WriteLine(g.neighbors("a"));
            //Console.WriteLine(g.neighbors("c"));
            //Console.WriteLine(g.neighbors("b"));

            Console.WriteLine("-------- BFSWalk --------");
            Console.WriteLine(g.BFSWalk("a"));
            Console.WriteLine("-------- BFSWalk --------\n");
            Console.WriteLine("-------- DFSWalk --------");
            Console.WriteLine(g.DFSWalk("a"));
            Console.WriteLine("-------- DFSWalk --------\n");

            g.CreateGraphVizFile(@"H:\output.txt", true);

            Console.WriteLine("----- Can I Reach From u & v -----");
            Console.WriteLine(g.CanReach("b", "e"));
            Console.WriteLine("----- Can I Reach From u & v -----\n");

            Console.WriteLine("----- Components -----");
            Console.WriteLine(g.Components());
            Console.WriteLine("----- Components -----\n");

            Console.WriteLine("----- Less Weight Path -----");
            Console.WriteLine(g.Dijkstra("a", "d"));
            Console.WriteLine("----- Less Weight Path -----\n");

            Console.ReadKey();
        }
Example #25
0
        private void Search(Graph g, int sourceVertex)
        {
            marked[sourceVertex] = true;
            count++;

            foreach (var vertex in g.AdjacentVertices(sourceVertex))
            {
                if (!marked[vertex])
                {
                    edgeTo[vertex] = sourceVertex;
                    Search(g, vertex);
                }
            }
        }
Example #26
0
    void Start()
    {
        var points = new List <GameObject>();

        Locations = new List <MapLocation>();
        foreach (Transform item in PointsContainer.transform)
        {
            points.Add(item.gameObject);
            Locations.Add(item.GetComponent <MapLocation>());
        }
        Graham     = new CHGraham(points);
        MeshMatrix = CreateMeshMatrix();

        LocationGraph = new Graph.Graph <MapLocation>();
    }
Example #27
0
 public CycleDetection(Graph.Graph g)
 {
     this.G  = g;
     visited = new bool[g.V];
     for (int i = 0; i < g.V; i++)
     {
         if (!visited[i])
         {
             if (DFS(i, i))
             {
                 isCycle = true;
                 break;
             }
         }
     }
 }
Example #28
0
 public CC(Graph.Graph g)
 {
     visited = new int[g.V];
     for (int i = 0; i < visited.Length; i++)
     {
         visited[i] = -1;
     }
     this.G = g;
     for (int i = 0; i < g.V; i++)
     {
         if (visited[i] == -1)
         {
             DFS(i, cccount);
             cccount++;
         }
     }
 }
Example #29
0
        static void Main(string[] args)
        {
            var lines = File.ReadAllLines(@"Resources\tinyG.txt");
            Graph g = new Graph(Convert.ToInt32(lines[0]));
            foreach (var str in lines.Skip(2))
            {
                int fromEdge = Convert.ToInt32(str.Split(' ')[0]);
                int toEdge = Convert.ToInt32(str.Split(' ')[1]);
                g.AddEdge(fromEdge, toEdge);
            }

            //DFS(g);
            //BFS(g);
            SymbolGraphTest();

            Console.WriteLine();
        }
Example #30
0
        public void SetExpression(EnvDTE.Expression exp)
        {
            root_expression = exp;

            if (root_expression == null)
            {
                graph = null;
            }
            else
            {
                RebuildGraph();
                MakeVertexCaptions();
                MakeVertexTooltips();
            }

            if (graphUpdated != null)
                graphUpdated(graph);
        }
Example #31
0
 private int[] pre;//遍历时的先导
 public Path(Graph.Graph g, int s, int t)
 {
     this.T = t;
     this.S = s;
     this.G = g;
     G.ValidateVertex(s);
     G.ValidateVertex(t);
     pre = new int[G.V];
     for (int i = 0; i < G.V; i++)
     {
         pre[i] = -1;
     }
     DFS(this.S, s);
     //foreach (var item in pre)
     //{
     //    Console.WriteLine(item);
     //}
 }
Example #32
0
        static void Main(string[] args)
        {
            Graph<Estacion> g = new Graph<Estacion>();
            Estacion tacubaya = new Estacion { Nombre = "Tacubaya"};
            Estacion constituyentes = new Estacion { Nombre = "Constituyentes"};
            Estacion snpedro = new Estacion { Nombre = "Sn Pedro de los Pinos"};
            Estacion snantonio = new Estacion { Nombre = "Sn Antonio"};

            Estacion observatorio = new Estacion { Nombre = "Observatorio"};
            Estacion patriotismo = new Estacion { Nombre = "Patriotismo"};
            Estacion juanacatlan = new Estacion { Nombre = "Juanacatlan"};
            Estacion xD = new Estacion { Nombre = "xD" };

            g.addNode(tacubaya);
            g.addNode(constituyentes);
            g.addNode(snpedro);
            g.addNode(snantonio);
            g.addNode(observatorio);
            g.addNode(patriotismo);
            g.addNode(juanacatlan);

            g.addNonDirectedVertex(constituyentes, tacubaya, 1005);
            g.addNonDirectedVertex(tacubaya, snpedro, 1084);
            g.addNonDirectedVertex(snpedro, snantonio, 606);
            g.addNonDirectedVertex(tacubaya, observatorio, 1262);
            g.addNonDirectedVertex(tacubaya, patriotismo, 1133);
            g.addNonDirectedVertex(tacubaya, juanacatlan, 1158);

            try
            {
                List<Node<Estacion>> estaciones = g.DijkstraList(juanacatlan, xD);
                Console.WriteLine("Ruta desde " + xD.Nombre + " => " + patriotismo.Nombre);
                Console.WriteLine("");
                foreach (var item in estaciones)
                {
                    Console.WriteLine(item.label.Nombre);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
Example #33
0
        private static void BFS(Graph g)
        {
            BFS bfs = new BFS(g, 0);
            for (int i = 0; i < g.Vertices; i++)
            {
                if (bfs.Marked(i))
                {
                    Console.Write(i + " ");
                }
            }
            Console.WriteLine();

            IEnumerable<int> path = bfs.Path(3);

            if (path != null)
            {
                path.ToList().ForEach(x => Console.Write(x + " "));
            }
            Console.WriteLine();
        }
Example #34
0
        private void ConstructGraph(string _path, string _delimiter)
        {
            _symbolTable = new Dictionary<string, int>();
            string[] lines = File.ReadAllLines(_path);

            foreach (var line in lines)
            {
                foreach (var item in line.Split('/'))
                {
                    if (!_symbolTable.ContainsKey(item))
                    {
                        _symbolTable.Add(item, _symbolTable.Count);
                    }
                }
            }

            _keys = _symbolTable.Keys.ToArray();

            _graph = new Graph(_symbolTable.Count);
        }
Example #35
0
        private void Search(Graph g, int vertex)
        {
            Queue<int> queue = new Queue<int>();
            queue.Enqueue(vertex);

            while (queue.Count != 0)
            {
                int element = queue.Dequeue();
                marked[element] = true;

                foreach (var item in g.AdjacentVertices(element))
                {
                    if (!marked[item])
                    {
                        marked[item] = true;
                        edgeTo[item] = vertex;
                        queue.Enqueue(item);
                    }
                }
            }
        }
        public GraphRandomStateGenerator(IModule module, PeReader.DefaultHost host, Log.Log logger, CfgManipulator cfgManipulator, Helper helperClass, Graph.Graph graph, MethodCfg methodCfg, bool debugging) {

            this.module = module;
            this.host = host;
            this.logger = logger;
            this.cfgManipulator = cfgManipulator;            
            this.helperClass = helperClass;
            this.graph = graph;
            this.methodCfg = methodCfg;
            this.debugging = debugging;

            // add local random generator variable
            this.tempRandomLocal = new LocalDefinition();
            this.tempRandomLocal.IsReference = false;
            this.tempRandomLocal.IsPinned = false;
            this.tempRandomLocal.IsModified = false;
            this.tempRandomLocal.Type = this.helperClass.systemRandom;
            this.tempRandomLocal.MethodDefinition = methodCfg.method;
            cfgManipulator.addLocalVariable(this.tempRandomLocal);


        }
        /// <summary>
        /// Creates instance of genetic algorithm
        /// </summary>
        /// <param name="graph">Graph on which algorithm will operate</param>
        /// <param name="problem">Problem for which algorithm will attempt to find solution</param>
        /// <param name="geneticOperators">Genetic operators used for breeding new generations</param>
        /// <param name="settings">General settings for solution finding process</param>
        /// <param name="startingPopulation">Starting population for algorithm</param>
        //TODO: Introduce SavedState complex type
        public GeneticAlgorithm(Graph graph, IProblem problem, GeneticOperators geneticOperators, 
            GeneticAlgorithmSettings settings, ICollection<Individual> startingPopulation = null, 
            uint currentGeneration = 0, Guid? id = null)
            : base(graph, problem, id)
        {
            if (geneticOperators == null)
                throw new ArgumentNullException(nameof(geneticOperators));
            if (!geneticOperators.IsValid())
                throw new ArgumentException("Genetic operators are not valid", nameof(geneticOperators));
            if (settings == null)
                throw new ArgumentNullException(nameof(settings));
            GeneticOperators = geneticOperators;
            Settings = settings;
            if (startingPopulation == null || startingPopulation.Count == 0 || !startingPopulation.All(IsIndividualValid))
                GenerateInitialPopulation();
            else
            {
                CurrentPopulation = new SortedSet<Individual>();
                foreach (var element in startingPopulation)
                    CurrentPopulation.Add(element);
            }

            CurrentGeneration = currentGeneration;
        }
Example #38
0
        static void Main(string[] args)
        {
            var graph = new Graph();

            var a = graph.CreateRoot(1);
            var b = graph.CreateVertex(2);
            var c = graph.CreateVertex(3);
            var d = graph.CreateVertex(4);
            var e = graph.CreateVertex(5);
            var f = graph.CreateVertex(6);
            var g = graph.CreateVertex(7);
            //var h = graph.CreateVertex(8);
            //var i = graph.CreateVertex(9);
            //var j = graph.CreateVertex(10);
            //var k = graph.CreateVertex(11);
            //var l = graph.CreateVertex(12);
            //var m = graph.CreateVertex(13);
            //var n = graph.CreateVertex(14);
            //var o = graph.CreateVertex(15);
            //var p = graph.CreateVertex(16);

            graph.InsertVertex(a);
            graph.InsertVertex(b);
            graph.InsertVertex(c);
            graph.InsertVertex(d);
            graph.InsertVertex(e);
            graph.InsertVertex(f);
            graph.InsertVertex(g);
            //graph.InsertVertex(h);
            //graph.InsertVertex(i);
            //graph.InsertVertex(j);
            //graph.InsertVertex(k);
            //graph.InsertVertex(l);
            //graph.InsertVertex(m);
            //graph.InsertVertex(n);
            //graph.InsertVertex(o);
            //graph.InsertVertex(p);

            //graph.LinkVertex(a, b);
            //graph.LinkVertex(a, c);

            //graph.LinkVertex(b, e);
            //graph.LinkVertex(b, d);

            //graph.LinkVertex(c, f);
            //graph.LinkVertex(c, d);

            //graph.LinkVertex(d, h);

            //graph.LinkVertex(e, g);
            //graph.LinkVertex(e, h);

            //graph.LinkVertex(f, h);
            //graph.LinkVertex(f, i);

            //graph.LinkVertex(g, j);
            //graph.LinkVertex(g, l);

            //graph.LinkVertex(h, j);
            //graph.LinkVertex(h, k);
            //graph.LinkVertex(h, m);

            //graph.LinkVertex(i, k);
            //graph.LinkVertex(i, n);

            //graph.LinkVertex(j, o);

            //graph.LinkVertex(k, p);

            //graph.LinkVertex(l, o);

            //graph.LinkVertex(m, o);
            //graph.LinkVertex(m, p);

            //graph.LinkVertex(n, p);

            graph.LinkVertex(a, b, 12);
            graph.LinkVertex(a, c, 10);

            graph.LinkVertex(b, c, 3);
            graph.LinkVertex(b, d, 9);
            graph.LinkVertex(b, e, 6);

            graph.LinkVertex(c, f, 20);

            graph.LinkVertex(d, e, 2);
            graph.LinkVertex(d, f, 4);

            graph.LinkVertex(e, g, 23);

            graph.LinkVertex(f, g, 14);

            var cost = graph.ShortestPath(a);
            //var edges = graph.findMinSpanningTree();
            var edges = graph.FindMinSpanTree();
            while (graph.ThrowGrenade())
            {
                Console.WriteLine("Throwing");
            }

            int steps = graph.Bfs(3);
            //Console.WriteLine(steps);
        }
Example #39
0
 public ConnectedComponentsFinder(Graph graph)
 {
     this.graph = graph;
     FindConnectedComponents();
 }
Example #40
0
        public void Test()
        {
            //Graph.GraphMatrix.Graph<int,int,int> graph=new Graph<int, int, int>();
            //graph.Insert(2);
            //graph.Insert(3);
            //graph.Insert(4);
            //graph.Insert(6);
            //graph.Insert(2, 0, 1, 2);
            //graph.Insert(3, 1, 2, 1);
            //graph.Insert(3, 0, 3, 6);
            //var res = graph.Prim();
            //Console.WriteLine(res.Count);
            //foreach (var primEdge in res)
            //{
            //    Console.WriteLine(primEdge);
            //}
            Action<Graph.GraphMatrix.Graph<int, int>, int, int> bfsAction = (Graph<int, int> g, int s, int w) =>
            {
                if (g.Status(w)==VStatus.Undiscovered)
                {
                    if (g.Priority(w) > g.Priority(s) + 1)
                    {
                        g.Priority(w, g.Priority(s) + 1);
                        g.Parent(w, s);
                    }
                }
            };
            Action<Graph.GraphMatrix.Graph<int, int>, int, int> dfsAction = (Graph<int, int> g, int s, int w) =>
            {
                if (g.Status(w) == VStatus.Undiscovered)
                {
                    if (g.Priority(w) > g.Priority(s) - 1)
                    {
                        g.Priority(w, g.Priority(s) - 1);
                        g.Parent(w, s);
                        return;
                    }
                }
            };
            Action<Graph.GraphMatrix.Graph<int, int>, int, int> primAction = (Graph<int, int> g, int s, int w) =>
            {
                if (g.Status(w) == VStatus.Undiscovered)
                {
                    if (g.Priority(w) > g.Weight(s,w))
                    {
                        g.Priority(w, g.Weight(s, w));
                        g.Parent(w, s);
                        
                    }
                }
            };
            IGraph<int,int> pGraph=new Graph<int, int>();
            pGraph.Insert(2);
            pGraph.Insert(3);
            pGraph.Insert(4);
            pGraph.Insert(6);
            pGraph.Insert(2, 0, 1, 2);
            pGraph.Insert(3, 1, 2, 2);
            pGraph.Insert(3, 0, 3, 6);
            pGraph.Insert(2, 2, 3, 5);
            pGraph.Insert(1, 0, 2, 1);
            pGraph.Prim();
            for (int i = 0; i < pGraph.N; i++)
            {
                Console.WriteLine(pGraph.Parent(i)); 
            }

        }
 //TODO: Why on earth not in ctor?
 /// <summary>
 /// Initialize the problem with graph data structure.
 /// </summary>
 /// <param name="graph">Graph that represents problem to solve.</param>
 public void Initialize(Graph graph)
 {
     if (graph == null) throw new ArgumentException(nameof(graph));
     if (_isInitialized) return;
     _currentCover = new HashSet<Node>(graph.Nodes);
     Graph = graph;
     _isInitialized = true;
 }
Example #42
0
        static void Main(string[] args)
        {
            Graph graph = new Graph();
            bool  flag  = true;

            Menu();
            while (flag)
            {
                Console.WriteLine("Ваш выбор: ");
                int n = int.Parse(Console.ReadLine());
                switch (n)
                {
                case 1:
                    Console.WriteLine("Введите название вершины: ");
                    string name = Console.ReadLine();
                    Console.WriteLine("Вершина добавлена с номером {0}", graph.AddVertex(name));
                    break;

                case 2:
                    Console.WriteLine("Введите первую вершину: ");
                    string v1 = Console.ReadLine();
                    Console.WriteLine("Введите вторую вершину: ");
                    string v2 = Console.ReadLine();
                    Console.WriteLine("Введите расстояние: ");
                    int d = int.Parse(Console.ReadLine());
                    graph.AddEdge(v1, v2, d);
                    break;

                case 3:
                    Console.WriteLine("Введите название вершины: ");
                    string vert = Console.ReadLine();
                    graph.DeleteVertex(vert);
                    break;

                case 4:
                    Console.WriteLine("Введите первую вершину: ");
                    string v1_ = Console.ReadLine();
                    Console.WriteLine("Введите вторую вершину: ");
                    string v2_ = Console.ReadLine();
                    graph.DeleteEdge(v1_, v2_);
                    break;

                case 5:
                    graph.WriteMatrix("input.txt");
                    break;

                case 6:
                    graph.Print();
                    break;

                case 7:
                    Console.WriteLine("Введите вершину: ");
                    string vertex = Console.ReadLine();
                    foreach (var v in graph.FindАdjacentVertexs(vertex))
                    {
                        Console.Write(v.Name + " ");
                    }
                    Console.WriteLine();
                    break;

                case 8:
                    Console.WriteLine("Введите вершину: ");
                    vertex = Console.ReadLine();
                    foreach (var v in graph.FindNonАdjacentVertexs(vertex))
                    {
                        Console.Write(v.Name + " ");
                    }
                    Console.WriteLine();
                    break;

                case 9:
                    Graph graph1 = graph.GetdisorientedGraph();
                    graph1.Print();
                    break;

                case 10:
                    Console.WriteLine("Введите вершину:");
                    var ve = Console.ReadLine();
                    foreach (var ver in graph.DFS(ve))
                    {
                        Console.WriteLine(ver.Name);
                    }
                    break;

                case 11:
                    int cnt = 0;
                    if (graph.IsDisorientedGraph())
                    {
                        foreach (var comp in graph.FindRelatedComponents())
                        {
                            cnt++;
                            Console.Write("{0} компонента связанности: ", cnt);
                            foreach (var _vertex in comp)
                            {
                                Console.Write(_vertex.Name + " ");
                            }
                            Console.WriteLine();
                        }
                    }
                    else
                    {
                        foreach (var comp in graph.FindStrongRelatedComponents())
                        {
                            cnt++;
                            Console.Write("{0} компонента сильной связанности: ", cnt);
                            foreach (var _vertex in comp)
                            {
                                Console.Write(_vertex + " ");
                            }
                            Console.WriteLine();
                        }
                    }
                    break;

                case 12:
                    cnt = 0;
                    foreach (var comp in graph.FindStrongRelatedComponents())
                    {
                        cnt++;
                        Console.Write("{0} компонента сильной связанности: ", cnt);
                        foreach (var _vertex in comp)
                        {
                            Console.Write(_vertex + " ");
                        }
                        Console.WriteLine();
                    }
                    break;

                case 13:
                    Graph copy = new Graph(graph);
                    graph = graph.GetdisorientedGraph();
                    Graph minGraph = graph.AlgBoruvka();
                    graph = copy;
                    minGraph.Print();
                    break;

                case 14:
                    Console.WriteLine(graph.FindVertexWithMinDistancees().Name);
                    break;

                case 15:
                    Console.Write("Центр графа: ");
                    foreach (var verte in graph.FindCenter())
                    {
                        Console.Write(verte.Name + " ");
                    }
                    Console.WriteLine();
                    break;

                case 16:
                    Console.WriteLine("Минимальные расстояния: ");
                    foreach (var edge in graph.GetMinDistancesForEachPair())
                    {
                        Console.WriteLine(edge.V1.Name + " " + edge.V2.Name + " " + edge.Distance);
                    }
                    break;

                case 17:
                    Console.WriteLine("Введите первую вершину: ");
                    v1 = Console.ReadLine();
                    Console.WriteLine("Введите вторую вершину: ");
                    v2 = Console.ReadLine();
                    Console.Write("Максимальный поток: {0} ", graph.maxFlow(v1, v2));
                    Console.WriteLine();
                    break;

                case 18:
                    flag = false;
                    break;
                }
            }
        }
 public static IEnumerable<Individual> AsDomainModel(this IEnumerable<IndividualEntity> entities, Graph graph, IProblem problem)
 {
     if (entities == null) return new List<Individual>();
     return entities.Where(e => e != null).Select(e => e.AsDomainModel(graph, problem));
 }
Example #44
0
        public static Graph CreateGraph(string path)
        {
            Graph       graph = new Graph();
            List <Edge> edges = new List <Edge>();
            List <Node> nodes = new List <Node>();

            string input = File.ReadAllText(path);

            if (input.Any(x => x.Equals('r')))
            {
                input = input.Replace("\r", "");
            }

            int arrDimension = Int32.Parse(input.Split("\n").ElementAt(0));

            graph.VerticesCount = arrDimension;

            input = input.Substring(2);
            int i = 0, j = 0;

            foreach (var row in input.Split('\n'))
            {
                j = 0;
                foreach (var col in row.Trim().Split(' '))
                {
                    var value = int.Parse(col.Trim());

                    if (value != 0)
                    {
                        if (!edges.Exists(x => x.Source == j && x.Destination == i))
                        {
                            var edge = new Edge
                            {
                                Source      = i,
                                Destination = j,
                                Weight      = int.Parse(col.Trim())
                            };

                            edges.Add(edge);

                            if (nodes.Exists(x => x.Id == i))
                            {
                                nodes.First(x => x.Id == i).Rank++;
                            }
                            else
                            {
                                nodes.Add(new Node {
                                    Id = i, Rank = 1
                                });
                            }

                            if (nodes.Exists(x => x.Id == j))
                            {
                                nodes.First(x => x.Id == j).Rank++;
                            }
                            else
                            {
                                nodes.Add(new Node {
                                    Id = j, Rank = 1
                                });
                            }
                        }
                    }
                    j++;
                }
                i++;
            }

            graph.EdgesCount = edges.Count;
            graph.Edges      = edges.ToArray();
            graph.Nodes      = nodes.ToArray();

            return(graph);
        }
Example #45
0
 public ExpressionGraph()
 {
     root_expression = null;
     graph = null;
 }
Example #46
0
 public void HandleConnectionRemoved(Graph.NodeConnector fromNodeConnector, Graph.NodeConnector toNodeConnector, bool input)
 {
 }
Example #47
0
 public void HandleConnectionAdded(Graph.NodeConnection connection, bool input)
 {
 }
 public DepthFirstSearch(Graph g, int s)
 {
     _marks = new bool[g.Vertice()];
     Search(g, s);
 }
Example #49
0
 private void InitializeGraph(String filePath)
 {
     comboBoxLayout.SelectedIndex = 0;
     labelTraversalResult.Text = String.Empty;
     comboBoxTraversalMethod.SelectedIndex = -1;
     try
     {
         _graph = GraphBuilder.BuildFromXmlFile<Char>(filePath);
     }
     catch (Exception)
     {
         MessageBox.Show("Error occured while parsing XML file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     textBoxStartWithLabel.Text = _graph.Root.Label.ToString(System.Globalization.CultureInfo.InvariantCulture);
     panelGraph.BackColor = Color.White;
     DrawGraph();
 }
 private static Individual AsDomainModel(this IndividualEntity entity, Graph graph, IProblem problem)
 {
     return new Individual(graph, problem, entity.CurrentSolution.Select(Convert.ToBoolean).ToArray(), entity.Id); 
 }
        public void generateGraph(int graphValidPathCount) {

            this.graph = new Graph.Graph(this.graphInterfaces, this.prng, this.graphDepth, this.graphDimension);

            ValidGraphPath[] validPaths = this.graph.generateValidPaths(graphValidPathCount);

            // build graph from the given paths
            this.graph.buildGraph(validPaths);

            if (this.debugging) {
                this.logger.dumpGraph(this.graph.startingNode, "paths", this.graphOnlyDumpVPaths);
            }
        }
Example #52
0
        public static Graph CreateGraph(int[,] matrix)
        {
            Graph       graph = new Graph();
            List <Edge> edges = new List <Edge>();
            List <Node> nodes = new List <Node>();

            graph.VerticesCount = matrix.GetLength(0);

            int i = 0, j = 0;

            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                j = 0;
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    var value = matrix[row, col];

                    if (value != 0)
                    {
                        if (!edges.Exists(x => x.Source == j && x.Destination == i))
                        {
                            var edge = new Edge
                            {
                                Source      = i,
                                Destination = j,
                                Weight      = value
                            };

                            edges.Add(edge);

                            if (nodes.Exists(x => x.Id == i))
                            {
                                nodes.First(x => x.Id == i).Rank++;
                            }
                            else
                            {
                                nodes.Add(new Node {
                                    Id = i, Rank = 1
                                });
                            }

                            if (nodes.Exists(x => x.Id == j))
                            {
                                nodes.First(x => x.Id == j).Rank++;
                            }
                            else
                            {
                                nodes.Add(new Node {
                                    Id = j, Rank = 1
                                });
                            }
                        }
                    }
                    j++;
                }
                i++;
            }

            graph.EdgesCount = edges.Count;
            graph.Edges      = edges.ToArray();
            graph.Nodes      = nodes.ToArray();

            return(graph);
        }
		public static void Main (string[] args)
		{
			Console.WriteLine ("Hello World!");
			Graph g = new Graph (5);
			g.AddVertex (1.ToString());
			g.AddVertex (2.ToString());
			g.AddVertex (3.ToString());
			g.AddVertex (4.ToString());
			g.AddVertex (5.ToString());
			for (int i = 0; i < 5; i++) {
				Console.WriteLine ("Added Vertex : " + g.GetVertexAtIndex (i).label);
			}
			Vertex v1 = g.GetVertexAtIndex (0);
			Vertex v2 = g.GetVertexAtIndex (1);
			Vertex v4 = g.GetVertexAtIndex (4);
			Console.WriteLine ("Adding Edge Between ");
			Console.Write (" " + v1.label + " and " + v2.label);
			g.AddEdge (v1, v2);
			Console.Write (", " + v1.label + " and " + v4.label);
			g.AddEdge (v1, v4);
			Console.WriteLine ();
			Console.WriteLine ("Vertex Edges Connected to");
			g.ShowEdgesOfVertex (v1);


			Graph gr = new Graph (10);

			gr.AddVertex ("A");
			gr.AddVertex ("B");
			gr.AddVertex ("C");
			gr.AddVertex ("D");
			gr.AddVertex ("E");
			gr.AddVertex ("F");
			gr.AddVertex ("G");
			gr.AddVertex ("H");
			gr.AddVertex ("I");
			gr.AddVertex ("J");

			Vertex m1 = gr.GetVertexAtIndex (0);
			Vertex m2 = gr.GetVertexAtIndex (1);
			Vertex m3 = gr.GetVertexAtIndex (2);
			Vertex m4 = gr.GetVertexAtIndex (3);
			Vertex m5 = gr.GetVertexAtIndex (4);
			Vertex m6 = gr.GetVertexAtIndex (5);
			Vertex m7 = gr.GetVertexAtIndex (6);
			Vertex m8 = gr.GetVertexAtIndex (7);
			Vertex m9 = gr.GetVertexAtIndex (8);
			Vertex m10 = gr.GetVertexAtIndex (9);

			gr.AddEdge (m1, m2);
			gr.AddEdge (m2, m3);
			gr.AddEdge (m3, m4);
			gr.AddEdge (m1, m5);
			gr.AddEdge (m5, m6);
			gr.AddEdge (m6, m7);
			gr.AddEdge (m1, m8);
			gr.AddEdge (m8, m9);
			gr.AddEdge (m9, m10);
			gr.DepthFirstSearch ();
			gr.BredthFirstSearch ();

			Console.ReadLine ();
		}
Example #54
0
        void RebuildGraph()
        {
            graph = new Graph<Object>();

            usedVertices = new SortedDictionary<string, int>();
            int root = graph.add(new ExpressionVertex(root_expression));
            BuildGraphRec(root_expression, root, 0);
        }