public static Dictionary <int, int> DSATUR(ListGraph graph) { var verticesColors = new Dictionary <int, int>(); var notColoredVertices = graph.Nodes; var adjacentVerticesColors = Enumerable.Range(0, notColoredVertices.Count).ToDictionary(k => k, v => new List <int>()); var usedColors = 1; while (notColoredVertices.Count != 0) { var vertexToColor = GetVertexToColor(notColoredVertices, adjacentVerticesColors); var availableColors = new HashSet <int>(Enumerable.Range(0, usedColors).Where(x => !adjacentVerticesColors[vertexToColor.Number].Contains(x))); var color = availableColors.Count != 0 ? availableColors.Min() : usedColors; usedColors = availableColors.Count != 0 ? usedColors : usedColors + 1; verticesColors[vertexToColor.Number] = color; notColoredVertices.Remove(vertexToColor); foreach (var neighbor in vertexToColor.Neighbors) { adjacentVerticesColors[neighbor.Number].Add(color); } } return(verticesColors); }
static void Main(string[] args) { var graph = new ListGraph(); var bob = new Vertex("Bob"); var alice = new Vertex("Alice"); var mark = new Vertex("Mark"); var rob = new Vertex("Rob"); var maria = new Vertex("Maria"); graph.AddVertex(bob); graph.AddVertex(alice); graph.AddVertex(mark); graph.AddVertex(rob); graph.AddVertex(maria); graph.AddEdge(bob, alice); graph.AddEdge(bob, rob); graph.AddEdge(alice, mark); graph.AddEdge(rob, mark); graph.AddEdge(alice, maria); graph.AddEdge(rob, maria); foreach (var vertex in ListGraph.DepthFirstTraversal(graph, bob)) { Console.WriteLine(vertex.Label); } foreach (var vertex in ListGraph.BreadthFirstTraversal(graph, bob)) { Console.WriteLine(vertex.Label); } }
static void Main(string[] args) { bool[,] boolMap = GetBoolMapFromTxt(robotMapPath); ListGraph <MapElement> robotGraph = BooleanMapToGraph(boolMap); Console.WriteLine("//////////////////////////////////GRAFO ROBOT//////////////////////////////////\n\n"); Node <MapElement> inicio = robotGraph.NodeList.Find(f => f.Element.Id == 73); robotGraph.RUNALL(robotGraph, inicio, 21); List <Airport> airports = new List <Airport>(); foreach (string json in File.ReadAllLines(airportJsonFile)) { airports.Add(JsonConvert.DeserializeObject <Airport>(json)); } bool[,] relations = GetRelations(airports); double?[,] distances = GetDistances(airports, relations); ListGraph <Airport> grafo = new MatrixGraph <Airport> { EdgesMatrix = distances, NodeDataList = airports }.GenerateListGraphFromMatrixGraph(); Console.WriteLine("\n\n\n\n//////////////////////////////////GRAFO RYANAIR//////////////////////////////////\n\n"); Node <Airport> inicioRyan = grafo.NodeList.Find(f => f.Element.Id == 73); grafo.RUNALL(grafo, inicioRyan, 21); Console.ReadLine(); }
public ListGraph <T> GenerateListGraphFromMatrixGraph() { ListGraph <T> listGraph = null; if (NodeDataList != null && EdgesMatrix != null) { listGraph = new ListGraph <T>(); for (int i = 0; i < NodeDataList.Count; i++) { listGraph.NodeList.Add(new Node <T> { Element = NodeDataList[i] }); } for (int i = 0; i < NodeDataList.Count; i++) { for (int j = 0; j < EdgesMatrix.GetLength(0); j++) { if (EdgesMatrix[j, i] != null && EdgesMatrix[j, i] != 0)//CORREGIR ARCHIVO DE DISTANCIAS { listGraph.NodeList[i].ElementList.Add(new NodeRelation <T> { Node = listGraph.NodeList[j], Edge = (double)EdgesMatrix[j, i] }); } } } } return(listGraph); }
public static void printPartition(int[] partition, ListGraph graph) { Console.Write("Partition 1: "); for (int count = 0; count < partition.Length; count++) if (partition[count] == 1) Console.Write(graph[count] + " "); Console.Write("\nPartition 2: "); for (int count = 0; count < partition.Length; count++) if (partition[count] == 2) Console.Write(graph[count] + " "); Console.WriteLine(); }
public static Dictionary <int, int> GIS(ListGraph graph) { var verticesColors = new Dictionary <int, int>(); var notColoredVertices = graph.Nodes; var adjacentVerticesColors = Enumerable.Range(0, notColoredVertices.Count).ToDictionary(k => k, v => new List <int>()); var color = 1; while (notColoredVertices.Count != 0) { var available = GetVerticesToColor(notColoredVertices, adjacentVerticesColors, color); var availableDegrees = Enumerable.Range(0, available.Count).ToDictionary(k => available[k], v => graph.Nodes[v].GetDegree()); while (available.Count != 0) { var minimum = availableDegrees.Aggregate((l, r) => l.Value < r.Value ? l : r); var minVertex = minimum.Key; var degree = minimum.Value; if (!adjacentVerticesColors[minVertex.Number].Contains(color)) { verticesColors[minVertex.Number] = color; notColoredVertices.Remove(minVertex); foreach (var neighbor in minVertex.Neighbors) { adjacentVerticesColors[neighbor.Number].Add(color); if (available.Contains(neighbor)) { available.Remove(neighbor); availableDegrees.Remove(neighbor); foreach (var neig in neighbor.Neighbors) { availableDegrees[neig]--; } } graph.RemoveDoubleEdge(new List <Node>() { neighbor, minVertex }); } } availableDegrees.Remove(minVertex); available.Remove(minVertex); } color++; } return(verticesColors); }
static void Main(string[] args) { int V = 4; ListGraph graph = new ListGraph(V); graph.addEdgeAtEnd(0, 1, 0); graph.addEdgeAtEnd(0, 4, 0); graph.addEdgeAtEnd(1, 2, 0); graph.addEdgeAtEnd(1, 3, 0); graph.addEdgeAtEnd(1, 4, 0); graph.addEdgeAtEnd(2, 3, 0); graph.addEdgeAtEnd(3, 4, 0); graph.printAdjList(); }
public static HashSet <Vertex> DepthFirstTraversal(ListGraph graph, Vertex root) { HashSet <Vertex> visited = new HashSet <Vertex>(); Stack <Vertex> stack = new Stack <Vertex>(); stack.Push(root); while (stack.Count > 0) { Vertex vertex = stack.Pop(); if (!visited.Contains(vertex)) { visited.Add(vertex); foreach (var adjacent in graph.GetAdjacentVertices(vertex)) { stack.Push(adjacent); } } } return(visited); }
public static HashSet <Vertex> BreadthFirstTraversal(ListGraph graph, Vertex root) { HashSet <Vertex> visited = new HashSet <Vertex>(); Queue <Vertex> queue = new Queue <Vertex>(); visited.Add(root); queue.Enqueue(root); while (queue.Count > 0) { Vertex vertex = queue.Dequeue(); foreach (var adjacent in graph.GetAdjacentVertices(vertex)) { if (!visited.Contains(adjacent)) { visited.Add(adjacent); queue.Enqueue(adjacent); } } } return(visited); }
const string FOLDER = "Graphs/"; //Path to the txt files that contain adjacency lists static void Main(string[] args) { string userIn; int data = -1; Console.WriteLine("Enter a number to test a class...\n" + "1. ListGraph \n" + "2. MarkovChain \n" + "3. BipartiteGraph \n"); try { userIn = Console.ReadLine(); data = Int32.Parse(userIn); } catch (Exception) { Console.WriteLine("Not a valid integer. Ending Program\n"); } switch (data) { case 1: //ListGraph ListGraph ports = new ListGraph(FOLDER + "airport.txt"); Console.WriteLine("Printing List..."); Console.WriteLine(ports + "\n"); //Inital print ports.addNode("LON"); ports.addEdge("LON", "MOB", 132); ports.addEdge("MOB", "LON", 132); Console.WriteLine("Printing Depth-Search and Breath-Search..."); ports.depthSearchPrint("LON"); ports.breathSearchPrint("LON"); //Print of the graph with a new node Console.WriteLine(); ports.removeNode("DFW"); Console.WriteLine("DFW Removed. Printing List...\n" + ports + "\n"); //New Print with DFW removed ports.depthSearchPrint("MOB"); //Follow two calls show that the list split into multiple graphs ports.breathSearchPrint("MOB"); Console.WriteLine(); ports.addEdge("MOB", "MSY", 111); ports.addEdge("MOB", "OKC", 222); ports.addEdge("MOB", "SHV", 333); ports.addEdge("MOB", "LIT", 444); ports.addEdge("MOB", "SAT", 555); ports.addEdge("MOB", "SFO", 777); Console.WriteLine("Printing Modified Graph in Depth-Seach, Breath-Search and Adj List..."); ports.depthSearchPrint("MOB"); ports.breathSearchPrint("MOB"); //Print of the graph reconnected into one graph ports.removeEdge("AUS", "SAT"); Console.WriteLine(ports + "\n"); /*Display nodes by traversing Array */ for (int count = 0; count < ports.length; count++) Console.Write(ports[count] + " "); Console.WriteLine(); break; case 2: ListMarkovChain graph = new ListMarkovChain(FOLDER + "Diagonal.txt"); Console.WriteLine(graph); double[,] moveResult = graph.move(3); double[] inital = { .5, .5 }; double[] result = graph.calculateProbability(inital, 3); for (int row = 0; row < moveResult.GetLength(1); row++) { for (int col = 0; col < moveResult.GetLength(1); col++) Console.Write(moveResult[row, col] + " "); Console.WriteLine(); } Console.WriteLine(); for (int count = 0; count < result.Length; count++) Console.Write(result[count] + " "); Console.WriteLine(); break; case 3: /* Graph that represents a square*/ ListGraph checkGraph = new ListGraph(FOLDER + "SquareGraph.txt"); Console.WriteLine("Square Graph"); int[] partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents a prism */ checkGraph = new ListGraph(FOLDER + "Prism.txt"); Console.WriteLine("Prism Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents a cube */ checkGraph = new ListGraph(FOLDER + "Cube.txt"); Console.WriteLine("Cube Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents a star */ checkGraph = new ListGraph(FOLDER + "Star.txt"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); Console.WriteLine("Star Graph"); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents a directional graph that returns to start at the end point */ checkGraph = new ListGraph(FOLDER + "LineGraph.txt"); Console.WriteLine("Directional Line Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents 2 connected squares */ checkGraph = new ListGraph(FOLDER + "ConnectedSquares.txt"); Console.WriteLine("2 Connected Squares Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents Binary Tree */ checkGraph = new ListGraph(FOLDER + "BinaryTree.txt"); Console.WriteLine("Binary Tree"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents a directional hourglass */ checkGraph = new ListGraph(FOLDER + "DirHourglass.txt"); Console.WriteLine("Directional Hourglass Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents an empty graph */ checkGraph = new ListGraph(FOLDER + "SingleLoop.txt"); Console.WriteLine("One node that loops Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); /*Graph that represents an empty graph */ checkGraph = new ListGraph(); Console.WriteLine("Empty Graph"); partition = Bipartitism.BipartiteGraph.getBipartition(checkGraph); printPartition(partition, checkGraph); if (Bipartitism.BipartiteGraph.isBipartite(checkGraph)) Console.WriteLine("Graph is bipartite."); else Console.WriteLine("Graph is not bipartite"); Console.WriteLine(); break; } }
//////////////////////////////////RUNING SEARCH ALGORITHMS+ grafo {Graph.ListGraph<Graph.Airport>} Graph.ListGraph<Graph.Airport> public static void RUNING_ALGORITHMS_ROBOT(ListGraph <MapElement> graph, Node <MapElement> inicio) { if (inicio != null) { } }
public static ListGraph <MapElement> BooleanMapToGraph(bool[,] map) { int x = map.GetLength(0); int y = map.GetLength(1); int id = 0; ListGraph <MapElement> grafo = new ListGraph <MapElement>(); for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { if (map[j, i]) { MapElement auxNode = new MapElement { Id = id, x = j, y = i }; grafo.NodeList.Add(new Node <MapElement> { Element = auxNode, ElementList = new List <NodeRelation <MapElement> >() }); } else { grafo.NodeList.Add(null); } id++; } } for (int i = 0; i < grafo.NodeList.Count; i++) { if (grafo.NodeList[i] == null) { continue; } if (i > 0 && i % x > 0) { if (grafo.NodeList[i - 1] != null) { grafo.NodeList[i].ElementList.Add(new NodeRelation <MapElement> { Node = grafo.NodeList[i - 1], Edge = 1 }); } } if (i + 1 < grafo.NodeList.Count && (i + 1) % x > 0) { if (grafo.NodeList[i + 1] != null) { grafo.NodeList[i].ElementList.Add(new NodeRelation <MapElement> { Node = grafo.NodeList[i + 1], Edge = 1 }); } } if (i + x < grafo.NodeList.Count) { if (grafo.NodeList[i + x] != null) { grafo.NodeList[i].ElementList.Add(new NodeRelation <MapElement> { Node = grafo.NodeList[i + x], Edge = 1 }); } } if (i - x > 0) { if (grafo.NodeList[i - x] != null) { grafo.NodeList[i].ElementList.Add(new NodeRelation <MapElement> { Node = grafo.NodeList[i - x], Edge = 1 }); } } } int k = 0; while (k < grafo.NodeList.Count) { if (grafo.NodeList[k] == null || grafo.NodeList[k].Element == null) { grafo.NodeList.RemoveAt(k); } else { k++; } } return(grafo); }
public void RUNALL(ListGraph <T> grafo1, Node <T> inicio, int destinationId) { List <Node <T> > deptProcessed = null; List <Node <T> > ampProcessed = null; Node <T> resultdept = grafo1.DepthSearchById(inicio, destinationId, null, ref deptProcessed); Node <T> resultamp = grafo1.AmplitudeSearchById(inicio, destinationId, null, ref ampProcessed); if (deptProcessed != null) { Console.WriteLine("\nDEPTH: "); foreach (Node <T> item in deptProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultdept; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } if (ampProcessed != null) { Console.WriteLine("\nAmplitude: "); foreach (Node <T> item in ampProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultamp; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } List <Node <T> > limitedDepthProcessed = null; List <Node <T> > IterativeDepthProcessed = null; Node <T> resultLimitedDepth = grafo1.LimitedDepthSearchById(5, inicio, destinationId, null, ref limitedDepthProcessed); Node <T> resultIterativeDepth = grafo1.IterativeDepthSearchById(3, 1, inicio, destinationId, null, ref IterativeDepthProcessed); if (limitedDepthProcessed != null && resultLimitedDepth != null) { Console.WriteLine("\nLimited: "); foreach (Node <T> item in limitedDepthProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultLimitedDepth; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } else { Console.WriteLine("\nNo fue encontrado por búsqueda limitada por profundidad 5"); } if (IterativeDepthProcessed != null && resultIterativeDepth != null) { Console.WriteLine("\nIterative: "); foreach (Node <T> item in IterativeDepthProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultIterativeDepth; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } List <Node <T> > memoryClimbingProcessed = null; List <Node <T> > bestFirstProcessed = null; Node <T> destination = grafo1.NodeList.Find(f => f.Element.Id == destinationId); Node <T> resultClimbingM = grafo1.MemoryHillClimbingSearchByElement(inicio, destination.Element, null, ref memoryClimbingProcessed); Node <T> resultBestFirst = grafo1.BestFirstSearchById(inicio, destinationId, null, ref bestFirstProcessed); if (memoryClimbingProcessed != null && resultClimbingM != null) { Console.WriteLine("\nSubida de la colina con memoria: "); foreach (Node <T> item in memoryClimbingProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultClimbingM; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } else { Console.WriteLine("\nNo fue encontrado por búsqueda subida de la colina con memoria"); } if (bestFirstProcessed != null && resultBestFirst != null) { Console.WriteLine("\nprimero el mejor: "); foreach (Node <T> item in bestFirstProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultBestFirst; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } else { Console.WriteLine("\nNo fue encontrado por búsqueda mejor el primero"); } List <Node <T> > climbingProcessed = null; List <Node <T> > dijkstraProcessed = null; Node <T> resultClimbing = grafo1.HillClimbingSearchByElement(inicio, destination.Element, null, ref climbingProcessed); Node <T> resultDijkstra = grafo1.UniformCostSearchById(inicio, destinationId, null, ref dijkstraProcessed); if (climbingProcessed != null && resultClimbing != null) { Console.WriteLine("\nClimbing sin memoria: "); foreach (Node <T> item in climbingProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultClimbing; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } else { Console.WriteLine("\nNo fue encontrado por búsqueda subida de la colina SIN memoria"); } if (dijkstraProcessed != null && resultDijkstra != null) { Console.WriteLine("\nDIJKSTRA: "); foreach (Node <T> item in dijkstraProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultDijkstra; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } else { Console.WriteLine("\nNo fue encontrado por DIJKSTRA"); } List <Node <T> > AEstrellaProcessed = null; Node <T> resultAEstrella = grafo1.AStartSearchByElement(inicio, destination.Element, null, ref AEstrellaProcessed); if (AEstrellaProcessed != null && resultAEstrella != null) { Console.WriteLine("\nA* busqueda **********************: "); foreach (Node <T> item in AEstrellaProcessed) { Console.Write(item.Element.Id + ", "); } //Console.WriteLine("Recorrido final: "); //Node<T> aux = resultAEstrella; //while (aux.SeachLbl.PreviousNode != null) //{ // Console.WriteLine(aux.Element.Id + ", "); // aux = aux.SeachLbl.PreviousNode; //} } else { Console.WriteLine("\nNo fue encontrado por búsqueda A*"); } }