public void showCycleDetection() { Graph graph = generateGraph(); CycleDetection cd = new CycleDetection(); TypologicalSort ts = new TypologicalSort(); MinimumSpanningTree mpt = new MinimumSpanningTree(); HashSet <Node> cycleSet = cd.findCycle(graph); Stack <Node> typologicalSortedStack = ts.topSort(graph); List <Edge> minimumSpanningList = mpt.getMinimumSpanningTree(graph); Console.WriteLine("\n\nCycle Detection: \n"); foreach (Node node in cycleSet) { Console.WriteLine(node.id); } // Not a good example as there are cycles in the graph. Console.WriteLine("\n\nTypological Sort: \n"); foreach (Node node in typologicalSortedStack) { Console.WriteLine(node.id); } Console.WriteLine("\n\nminumum spanning tree: \n"); foreach (Edge edge in minimumSpanningList) { Console.WriteLine(edge.from.id + " , " + edge.to.id); } }
public bool PrimaSMSTAlgorithm() { VisitedNodes.Add(InnerGraph.SetOfNodes[0]); for (; VisitedNodes.Count < InnerGraph.QuantityOfNodes;) { Node Start = new Node(); Node Finish = new Node(); // maybe throw infinity to group of special onjects and instruments fo algorithm Edge CurrentEdge = new Edge { Weight = double.PositiveInfinity }; for (int Index = 0; Index < InnerGraph.QuantityOfNodes; Index++) { if (VisitedNodes.Contains(InnerGraph.SetOfNodes[Index])) { foreach (Node Incomer in InnerGraph.SetOfNodes[Index].Incomers.Where(Node => Node != null && !VisitedNodes.Contains(Node))) { if (CurrentEdge.Weight > InnerGraph.FindEdge(InnerGraph.SetOfNodes[Index], Incomer).Weight) { CurrentEdge = InnerGraph.FindEdge(InnerGraph.SetOfNodes[Index], Incomer); Start = CurrentEdge[0]; Finish = CurrentEdge[1]; } } } } VisitedNodes.Add(Finish); MinimumSpanningTree.Add(InnerGraph.FindEdge(Start, Finish)); } return(VisitedNodes.Count.Equals(InnerGraph.QuantityOfNodes)); }
public void TestMinimumSpanningTreeUndirectedGraph() { IGraph graph = new Graph(); graph.AddNode(new Node("1")); graph.AddNode(new Node("2")); graph.AddNode(new Node("3")); graph.AddNode(new Node("4")); graph.AddNode(new Node("5")); graph.BuildEdge("1", "2", 8); graph.BuildEdge("1", "3", 4); graph.BuildEdge("1", "4", 2); graph.BuildEdge("1", "5", 3); graph.BuildEdge("2", "4", 15); graph.BuildEdge("2", "3", 9); graph.BuildEdge("3", "4", 10); graph.BuildEdge("3", "5", 7); graph.BuildEdge("4", "5", 9); MinimumSpanningTree mst = new MinimumSpanningTree(graph); WeightedTraversalResult result = mst.Run(); Assert.Equal("1,4,5,3,2", string.Join(",", result.Nodes.Select(node => node.ID))); Assert.Equal(17, result.TotalWeight); }
public void MinimumSpanningTree_DirectedGraph_ValidMinimumSpanningTree() { //Arrange var sut = new Graph <string>(); sut.AddVertex(TestVertex1); sut.AddVertex(TestVertex2); sut.AddVertex(TestVertex3); sut.AddVertex(TestVertex4); sut.AddVertex(TestVertex5); sut.AddDirectedEdge(TestVertex1, TestVertex2, 1); sut.AddDirectedEdge(TestVertex1, TestVertex3, 2); sut.AddDirectedEdge(TestVertex2, TestVertex3, 3); sut.AddDirectedEdge(TestVertex4, TestVertex5, 135); sut.AddDirectedEdge(TestVertex4, TestVertex5, 13); sut.AddDirectedEdge(TestVertex2, TestVertex5, 5); //Act var result = new MinimumSpanningTree <string>(sut); //Assert foreach (var vertex in sut.Vertices) { Assert.Contains(vertex, result.Vertices); } foreach (var edge in result.Edges) { Assert.Contains(edge, sut.Edges); } }
public string OnGetPruferCall() { var(tree, vertices) = MinimumSpanningTree.GetPruferCode(_graphMatrix); for (int i = 0; i < vertices.Count; ++i) { vertices[i] += 1; } string code = String.Join(" ", vertices); if (code.Equals("")) { code = "Empty"; } _view.AppendToLog($"{_logEntryNumber++}: Prufer's code:" + Environment.NewLine + "Matrix: " + Environment.NewLine + MatrixPrinter.GetMatrix(tree) + $"Code: {code}" + Environment.NewLine + Environment.NewLine); return(code); }
public void OnDecodePruferCall(List <int> code) { var graphMatrix = MinimumSpanningTree.DecodePrufer(code); if (_graphMatrix == null) { _graphMatrix = new GraphMatrix(code.Count + 2, 1, -10, 10); _graphMatrix.SetAdjacencyMatrix(graphMatrix); _graphMatrix.SetWeightMatrix(graphMatrix); _graphMatrix.SetSstMatrix(graphMatrix); _graphGenerated = false; _sstGenerated = true; _flowNetworkGenerated = false; } else { _graphMatrix.SetSstMatrix(graphMatrix); } string pruferCode = String.Join(" ", code); _view.AppendToLog($"{_logEntryNumber++}: Prufer's Decode:" + Environment.NewLine + "Matrix: " + Environment.NewLine + MatrixPrinter.GetMatrix(graphMatrix) + $"Code: {pruferCode}" + Environment.NewLine + Environment.NewLine); _graphMatrix.OutputToFileSst(); UpdateViewGraphImage(); }
public void TestMinimumSpanningTreeDirectedGraph() { IGraph graph = new Graph(true); graph.AddNode(new Node("1")); graph.AddNode(new Node("2")); graph.AddNode(new Node("3")); graph.AddNode(new Node("4")); graph.AddNode(new Node("5")); graph.AddNode(new Node("6")); graph.AddNode(new Node("7")); graph.AddNode(new Node("8")); graph.BuildEdge("1", "2", 18); graph.BuildEdge("1", "7", 10); graph.BuildEdge("2", "8", 7); graph.BuildEdge("2", "6", 11); graph.BuildEdge("3", "1", 2); graph.BuildEdge("3", "4", 6); graph.BuildEdge("3", "6", 21); graph.BuildEdge("5", "1", 5); graph.BuildEdge("5", "2", 4); graph.BuildEdge("6", "1", 19); graph.BuildEdge("7", "3", 17); graph.BuildEdge("7", "4", 3); graph.BuildEdge("7", "5", 3); graph.BuildEdge("8", "6", 9); MinimumSpanningTree mst = new MinimumSpanningTree(graph); WeightedTraversalResult result = mst.Run(); Assert.Equal(33, result.TotalWeight); Assert.Equal("3,1,7,4,5,2,8,6", string.Join(",", result.Nodes.Select(node => node.ID))); }
static void MainF(string[] args) { #if false Reader = new StreamReader(@"Graph\MST\test\test.txt"); #else Reader = new StreamReader(Console.OpenStandardInput()); #endif t = ReadInt(); for (int i = 0; i < t; i++) { ns = ReadIntArray(); n = ns[0]; m = ns[1]; dis = new double[n, n]; for (int k = 0; k < n; k++) { for (int h = k + 1; h < n; h++) { dis[k, h] = double.MaxValue; } } List <Pair>[] graph = Enumerable.Range(0, n).Select(s => new List <Pair>()).ToArray();; for (int k = 0; k < m; k++) { ns = ReadIntArray(); var s = ns[0] - 1; var d = ns[1] - 1; var weight = Math.Log10(ns[2]); graph[s].Add(new Pair(s, d, weight) { We = ns[2] }); graph[d].Add(new Pair(d, s, weight) { We = ns[2] }); } List <Pair> path; MinimumSpanningTree.GetMinimumSpanningTree(graph, out path); long result = 1; foreach (var item in path) { result = (result * item.We) % 1000000007; } Console.WriteLine(result); } Reader.Close(); }
public List <int> SearchOptimalPath(int startedVertice) { var numberOfVertices = _graph.AdjacencyMatrix.GetLength(0); var edges = _graph.InitializeEdgesInUndirectedGraph(Enums.VerticesType.Uncycle); var minimumSpanningTree = new MinimumSpanningTree(startedVertice, numberOfVertices, edges); var depthFirstSearch = new DepthFirstSearch(); var path = depthFirstSearch.PreorderTraversal(startedVertice, minimumSpanningTree.TreeMatrix); return(path); }
public void OnTotalSstCall(IPresenterConnectedDialog dialog) { int total = MinimumSpanningTree.TotalStAmount(_graphMatrix); string totalStr = total > 0 ? total.ToString() : $"More than {Int32.MaxValue}"; _view.AppendToLog($"{_logEntryNumber++}: Kirchhoff's total amount of spanning trees:" + Environment.NewLine + $"Total amount: {totalStr}" + Environment.NewLine + Environment.NewLine); }
private void Form1_Load_1(object sender, EventArgs e) { // maak knopen aan (hardcoded) Knoop h1 = new Knoop("H1"); Knoop h2 = new Knoop("H2"); Knoop h3 = new Knoop("H3"); Knoop h4 = new Knoop("H4"); Knoop h5 = new Knoop("H5"); Knoop h6 = new Knoop("H6"); Knoop h7 = new Knoop("H7"); Knoop h8 = new Knoop("H8"); Knoop h9 = new Knoop("H9"); Knoop h10 = new Knoop("H10"); knopen.Add(h1); knopen.Add(h2); knopen.Add(h3); knopen.Add(h4); knopen.Add(h5); knopen.Add(h6); knopen.Add(h7); knopen.Add(h8); knopen.Add(h9); knopen.Add(h10); // maak kanten aan (hardcoded) kanten.Add(new Kant(h1, h2, 20)); kanten.Add(new Kant(h1, h3, 45)); kanten.Add(new Kant(h1, h10, 45)); kanten.Add(new Kant(h2, h3, 30)); kanten.Add(new Kant(h2, h5, 25)); kanten.Add(new Kant(h2, h8, 100)); kanten.Add(new Kant(h2, h10, 30)); kanten.Add(new Kant(h3, h4, 45)); kanten.Add(new Kant(h4, h5, 75)); kanten.Add(new Kant(h4, h6, 40)); kanten.Add(new Kant(h5, h6, 75)); kanten.Add(new Kant(h5, h8, 90)); kanten.Add(new Kant(h6, h7, 80)); kanten.Add(new Kant(h6, h9, 40)); kanten.Add(new Kant(h7, h8, 15)); kanten.Add(new Kant(h8, h9, 45)); kanten.Add(new Kant(h8, h10, 50)); // bepaal 'Minimum Spanning Tree' via prim algoritme MinimumSpanningTree mst = new MinimumSpanningTree(); DataTable table = mst.BuildMatrixTable("PrimTable", knopen, kanten); FillGridView(table); List <Kant> geselecteerdeKanten = mst.Get(table, knopen, kanten); DisplayResult(geselecteerdeKanten); }
public void MinimumSpanningTree_EmptyGraph_EmptyGraph() { //Arrange var sut = new Graph <string>(); //Act var result = new MinimumSpanningTree <string>(sut); //Assert Assert.True(result.IsEmpty); }
public void CreatingMinimumSpanningTreeV2ShouldReturnCorrectTreeMatrix() { var graph = new Graph(_dirPathSample + "v2Graph.json"); var edges = graph.InitializeEdgesInUndirectedGraph(Enums.VerticesType.Uncycle); var minimumSpanningTree = new MinimumSpanningTree(0, 4, edges); var correctMinimumSpanningTree = new Graph(_dirPathCorrect + "v2GraphTreeMatrix.json"); minimumSpanningTree.TreeMatrix.ShouldBeEquivalentTo(correctMinimumSpanningTree.AdjacencyMatrix); _output.WriteLine(minimumSpanningTree.ToString()); }
public void PreorderTraversalShouldReturnCorrectPath() { var graph = new Graph(_dirPathSample + "v1Graph.json"); graph.InitializeEdgesInUndirectedGraph(Enums.VerticesType.Uncycle); var edges = graph.Edges; var startedVertice = 0; var minimumSpanningTree = new MinimumSpanningTree(startedVertice, 6, edges); var dfs = new DepthFirstSearch(); var correctPath = new List<int> { 0, 2, 3, 1, 4, 5, 0 }; var path = dfs.PreorderTraversal(startedVertice, minimumSpanningTree.TreeMatrix); path.ShouldBeEquivalentTo(correctPath); ShowPath(path); }
/// <summary> /// Using Findsub tree develop from starting tree (root) to minimum spanning tree /// Don't if it should be bool type</summary> /// <returns></returns> public bool KruskalSMSTAlgorithm() { InnerGraph.SetOfEdges = InnerGraph.SetOfEdges.OrderBy(Edge => Edge.Weight).ToList <Edge>(); for (int Index = 0; Index < InnerGraph.QuantityOfEdges; Index++) { Node StartNode = FindSubTree(InnerGraph.SetOfEdges[Index][0]); Node EndNode = FindSubTree(InnerGraph.SetOfEdges[Index][1]); if (!StartNode.Equals(EndNode)) { MinimumSpanningTree.Add(InnerGraph.SetOfEdges[Index]); InnerGraph.SetOfNodes[EndNode.Index] = StartNode; } } return(true); }
public static int GetMinimumCost(int[,] graph, int k) { var costs = WarshallShortestPath.GetShortestCostsAndPath(graph).Item1; var newGraph = Enumerable.Range(0, k).Select(e => new List <Pair>()).ToArray(); for (int a = 0; a < k; a++) { for (int b = a + 1; b < k; b++) { newGraph[a].Add(new Pair(a, b, costs[a, b])); newGraph[b].Add(new Pair(b, a, costs[a, b])); } } List <Pair> path; return(MinimumSpanningTree.GetMinimumSpanningTree(newGraph, out path)); }
public void Execute(Graph graph) { System.Console.WriteLine("De kerker schudt op zijn grondvesten, de tegenstander in een aangrezende hallway is vermorzeld!" + "Een donderend geluid maakt duidelijk dat gedeeltes van de kerker zijn integestort..."); MinimumSpanningTree algorithm = new MinimumSpanningTree(); HashSet <Edge> edges = algorithm.Execute(graph); foreach (var edge in graph.Edges) { if (!edges.Contains(edge)) { edge.Walkable = false; } } List <Edge> edgesFromStart = graph.StartPoint.Edges.ToList(); Random random = new Random(); int r = random.Next(edgesFromStart.Count); edgesFromStart[r].Weight = 0; }
public void OnKruskalAlgorithmCall(IPresenterConnectedDialog dialog) { (var tree, int iter) = MinimumSpanningTree.Kruskal(_graphMatrix); var builder = new StringBuilder(); _sstGenerated = true; int weight = 0; if (tree.Count > 0) { for (int i = 0; i < tree.Count; ++i) { builder.AppendLine((tree[i].Item1 + 1) + " <-> " + (tree[i].Item2 + 1)); weight += _graphMatrix.GetWeightMatrix()[ Math.Min(tree[i].Item1, tree[i].Item2), Math.Max(tree[i].Item1, tree[i].Item2)]; } } else { builder.Append("SST not found"); _sstGenerated = false; } _view.AppendToLog($"{_logEntryNumber++}: Kruskal's Algorithm:" + Environment.NewLine + builder.ToString() + $"Weight: {weight}" + Environment.NewLine + $"Iterations: {iter}" + Environment.NewLine + Environment.NewLine); dialog.SetData("Built SST"); _graphMatrix.OutputToFileWithKruskal(); UpdateViewGraphImage(); }
/// <summary> /// Einstiegspunkt des Programms /// </summary> public static void Main() { // Wir legen ein neues Array an und testen unser Programm! Point[] pArray = new Point[10]; pArray[0] = new Point(8, 24); pArray[1] = new Point(9, 12); pArray[2] = new Point(3, 7); pArray[3] = new Point(13, 30); pArray[4] = new Point(12, 9); pArray[5] = new Point(4, 8); pArray[6] = new Point(8, 28); pArray[7] = new Point(10, 11); pArray[8] = new Point(28, 12); pArray[9] = new Point(6, 18); // Erstellung eines neuen Geographen GeoGraph g = new GeoGraph(pArray); // Erstellung eines minimalen Spannbaums MinimumSpanningTree tree = new MinimumSpanningTree(g); // Damit das Fenster offen bleibt, müssen wir hier Console.ReadKey() ausführen: Console.ReadKey(); }
public void Generate() { // Dungeongeneration implementiert annhähernd nach https://www.gamasutra.com/blogs/AAdonaac/20150903/252889/Procedural_Dungeon_Generation_Algorithm.php List <Room> rooms = new List <Room>(); // erstes Erstellen der Räume for (int i = 0; i < Args.Rooms; i++) { Room r = MakeRoom(); if (r != null) { rooms.Add(r); } } Vector[] centerPoints = new Vector[rooms.Count]; for (int i = 0; i < rooms.Count; i++) { centerPoints[i] = rooms[i].CenterPos; } DelaunayTriangulation triang = new DelaunayTriangulation(new Vector(Fields.GetLength(0), Fields.GetLength(1)), centerPoints); MinimumSpanningTree mst = new MinimumSpanningTree(triang); List <Edge> edges = new List <Edge>(); edges.AddRange(mst.Edges); edges.AddRange(rnd.PickElements(triang.Edges.Where(x => !mst.Edges.Contains(x)), Args.LeaveConnectionPercentage)); // lässt manche redundante Verbindungen da, damit Dungeon nicht linear ist List <Corridor> corridors = new List <Corridor>(); foreach (Edge e in edges) // versucht, Räume anhand der bestimmten Verbindungen mit Korridoren zu verbinden { Corridor c = ConnectRooms(Room.GetRoomByPosition(rooms, e.A), Room.GetRoomByPosition(rooms, e.B)); if (c != null) { corridors.Add(c); c.A.Connections.Add(c); c.B.Connections.Add(c); } } StartRoom = FindRoomWithMostConnections(rooms); RemoveUnreacheableRooms(rooms, StartRoom); Rooms = rooms.ToArray(); for (int x = 0; x < Fields.GetLength(0); x++) { for (int y = 0; y < Fields.GetLength(1); y++) { Fields[x, y].SetFieldTypeAndAnimation(Fields); } } List <Rectangle> b = new List <Rectangle>(); // Bounding-Rechtecke der Räume und Korridore foreach (Room r in rooms) { b.AddRange(r.Bounds); } foreach (Corridor c in corridors) { b.AddRange(c.Bounds); } Bounds = b.ToArray(); }