protected override object SolvePart1() { var(x, y) = (0, 0); var map = Input .ToDictionary(l => l.ToArray() .ToDictionary(c => (X: x++, Y: y), c => c), c => (x, y) = (0, y + 1)) .SelectMany(i => i.Key) .ToDictionary(i => i.Key, i => i.Value); var keys = "abcdefghijklmnopqrstuvwxyz".ToList(); var doors = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList(); var gotKeys = new List <char>(); var openedDoors = new List <char>(); var entrance = map.Single(p => p.Value == '@'); //var manhattanKeys = allKeys.Select(k => NumberTheory.ManhattanDistance(entrance.Key, k.Key)); //var manhattanDoors = allDoors.Select(k => NumberTheory.ManhattanDistance(entrance.Key, k.Key)); var steps = 0; // The loop. var currentLocation = entrance.Key; while (keys.Count > 0) { var allKeys = map.Where(p => keys.Contains(p.Value)).ToList(); var allDoors = map.Where(p => doors.Contains(p.Value)).ToList(); //var possibleLocations = map.Where(p => p.Value != '#').ToDictionary(p => p.Key, p => p.Value); var possibleLocations = map.Where(p => p.Value != '#' && !doors.Contains(p.Value) && !gotKeys.Contains(p.Value)).ToDictionary(p => p.Key, p => p.Value); var pathCosts = GetPathCosts(map, possibleLocations); var costsToKeys = new Dictionary <char, LinkedList <PathFindingBase <(int, int)> > >(); foreach (var key in allKeys) { var shortPath = Dijkstras.CalculateShortestPathBetween(currentLocation, key.Key, pathCosts); if (shortPath.Count > 0) { costsToKeys.Add(key.Value, shortPath); } } var closest = costsToKeys.First(c => c.Value.Count == costsToKeys.Min(p => p.Value.Count)); map[currentLocation] = '.'; map[closest.Value.Last().Destination] = '.'; gotKeys.Add(closest.Key); keys.Remove(closest.Key); doors.Remove(closest.Key.ToString(CultureInfo.InvariantCulture).ToUpperInvariant()[0]); steps += closest.Value.Count; currentLocation = closest.Value.Last().Destination; } // Find cost to closest key and door or cost to available door. return(null); }
public void GetShortestPath() { var graph = GetGraph(); var shortestPath = Dijkstras <int> .GetShortestPath(graph, 1, 6); Assert.Equal(new[] { 1, 3, 6 }, shortestPath); }
public void StartAlgorithmDijkstra() { Dijkstras algo = new Dijkstras(); algo.StartAlgorithm(map.GetStartPoint(), map.GetEndPoint(), this); Visualize(algo.GetPath(), algo.GetAlgoSteps()); }
IEnumerator Delayed() { yield return(new WaitForEndOfFrame()); var nodes = FindObjectsOfType <Node>(); Dijkstras.FindPath(nodes[0], nodes[200]); }
//https://leetcode.com/problems/network-delay-time/ public int NetworkDelayTime(int[][] times, int N, int K) { var diGraph = GraphUtilities.GetDiGraphFromWeightedEdges(times, N); var shortestDistances = Dijkstras <int> .GetShortestDistancesFrom(diGraph, K - 1); var maxTime = shortestDistances.Values.Max(); return(maxTime == int.MaxValue? -1: maxTime); }
private static (List <string> route, long totalTime) FindShortestRoute(string start, string destination) { var(graph, stationMap) = GraphCreator.CreateGraphFromFile(); var startIndex = stationMap[start]; var endIndex = stationMap[destination]; var(distances, parents) = Dijkstras.Calculate(graph, startIndex, stationMap.Count); var path = Dijkstras.GetPath(endIndex, parents); var route = path?.Select(i => stationMap.Single(d => d.Value == i).Key).ToList(); return(route, distances[stationMap[destination]]);
public void GetShortestDirectedDistances() { var graph = GetDirectedGraph(); var distances = Dijkstras <int> .GetShortestDistancesFrom(graph, 0); Assert.Equal(0, distances[0]); Assert.Equal(7, distances[1]); Assert.Equal(9, distances[2]); Assert.Equal(20, distances[3]); Assert.Equal(26, distances[4]); Assert.Equal(11, distances[5]); }
public HashSet<Vector3> paintRoomAroundLine (Edge e0, int w, int h){ var edges = (Edge.straightenEdge(e0)); var hallwayPoints = new HashSet<Vector3>(); Debug.DrawLine(e0.v1,e0.v2,Color.green,float.PositiveInfinity,false); foreach (Edge e in edges){ var angle = Vector3.Angle(e.slope,Vector3.forward); if ( Mathf.Approximately(90,angle)) { var path = Dijkstras.ASTAR(graph,e.v1,e.v2); hallwayPoints.UnionWith(path); Debug.DrawLine(e.v1,e.v2,Color.blue,float.PositiveInfinity,false); } else { Debug.DrawLine(e.v1,e.v2,Color.red,float.PositiveInfinity,false); } } return hallwayPoints; }
public void Refresh() { Dijkstras.ConnectionList connections = Dijkstras.GetConnections(this); foreach (var connection in connections) { if (Weight == 0 && !Mathf.Approximately(connection.to.getWeight(), 0) || Mathf.Sign(connection.to.getWeight()) != Mathf.Sign(Weight)) { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.tag = "Border"; DestroyImmediate(cube.GetComponent <Collider>()); Material standardShaderMaterial = cube.GetComponent <MeshRenderer>().material = wallMat; cube.transform.position = Vector3.Lerp(transform.position, connection.to.transform.position, .5f); cube.transform.localScale = Vector3.one * .2f; cube.transform.LookAt(connection.to.transform); cube.transform.localScale += Vector3.right * .25f; //Destroy(cube, 1f); } } }
public Edge[] PopulateEdges(float option) { foreach (var v in vertices) { foreach (var w in vertices) { if (v == w) { continue; } if (edges.Find(e => (e.A == v && e.B == w) || (e.A == w && e.B == v)) == null) { CreateEdge(v, w); } } } List <Edge> important = new List <Edge>(); while (edges.Count > 0) { edges.Sort((e1, e2) => e2.dist2().CompareTo(e1.dist2())); // ordena - mais longa primeiro var candidate = edges[0]; RemoveEdge(candidate); var d = new Dijkstras(); d.Initialize(vertices.ToArray(), candidate.A, candidate.B, gdh, gah); d.Run(); if (d.FindDistance() > 1000 || candidate.dist2() < option) // remover a conexão causou a disconexão do grafo { important.Add(candidate); } } foreach (var i in important) { CreateEdge(i.A, i.B); // restitui apenas os importantes } return(edges.ToArray()); }
public static void Test() { Dijkstras <char> g = new Dijkstras <char>(); g.add_vertex('A', new Dictionary <char, int>() { { 'B', 7 }, { 'C', 8 } }); g.add_vertex('B', new Dictionary <char, int>() { { 'A', 7 }, { 'F', 2 } }); g.add_vertex('C', new Dictionary <char, int>() { { 'A', 8 }, { 'F', 6 }, { 'G', 4 } }); g.add_vertex('D', new Dictionary <char, int>() { { 'F', 8 }, { 'I', 3 } }); g.add_vertex('E', new Dictionary <char, int>() { { 'H', 1 } }); g.add_vertex('F', new Dictionary <char, int>() { { 'B', 2 }, { 'C', 6 }, { 'D', 8 }, { 'G', 9 }, { 'H', 3 } }); g.add_vertex('G', new Dictionary <char, int>() { { 'C', 4 }, { 'F', 9 } }); g.add_vertex('H', new Dictionary <char, int>() { { 'E', 1 }, { 'F', 3 } }); g.add_vertex('I', new Dictionary <char, int>() { }); g.ShortestPath('A', 'I').ForEach(x => Console.WriteLine(x)); }
private IEnumerator DijkstraTimeLeft() { float distance = 0; float max = 0; do { if (bModoStop) { yield return(new WaitUntil(() => bModoStop == false)); } var d = new Dijkstras(); d.Initialize(listOfNodes, firewallNode, inputNode, findDistanceDij, findNeiDij); d.Run(); distance = d.FindDistance(); max = Mathf.Max(max, distance); hud.SetProgressBar(100f * distance / max); yield return(new WaitForEndOfFrame()); }while(distance > 0); }
void drawEntrancePath(Room room, List <Vector3> white) { var entrances = room.getCellsByAttribute(FaceTypes.ENTRANCE); foreach (Cell c in entrances) { white.Add(c.center); } var edgeMap = EdgeMap.constructEdgemapFromPoints(room.pointsInRoom); var edges = GenerateMap.getDelaunayFromPoints(white).ToList(); edges = new Prims().execute(edges).ToList(); foreach (Edge e in edges) { var path = Dijkstras.ASTAR(edgeMap, e.v1, e.v2); for (int i = 0; i < path.Count - 1; i++) { Debug.DrawLine(path[i], path[i + 1], Color.grey, float.PositiveInfinity, false); } white.AddRange(path); } }
private void readJson(JSONObject json) { boxers = new List <Boxer>(); foreach (JSONObject r in json.GetField("boxers").list) { boxers.Add(new Boxer(r)); } managers = new List <Manager>(); foreach (JSONObject r in json.GetField("managers").list) { managers.Add(new Manager(r)); } capitols = new List <Capitol>(); foreach (JSONObject r in json.GetField("capitols").list) { capitols.Add(new Capitol(r)); } towns = new List <Town>(); foreach (JSONObject r in json.GetField("towns").list) { towns.Add(new Town(r)); } calendar = new Calendar(json.GetField("calendar")); regions = new List <Region>(); foreach (JSONObject r in json.GetField("regions").list) { regions.Add(new Region(r)); } dijkstras = new Dijkstras(json.GetField("dijkstras")); updateBoxerDistribution(); }
public DataPool() { boxers = new List <Boxer> (); managers = new List <Manager> (); capitols = new List <Capitol>(); towns = new List <Town> (); exerciseDescriptions = new Dictionary <string, string> (); exerciseProgress = new Dictionary <string, List <List <int> > > (); firstNames = new List <string>(); lastNames = new List <string>(); townNames = new List <string>(); tournamentNames = new List <string>(); backTournamentNames = new List <string>(); calendar = new Calendar(); dijkstras = new Dijkstras(); regions = new List <Region>(); loadNameData(); }
public void Dijkstra(int startNode) { Dijkstras dijkstra = new Dijkstras(adjacencyMatrix, startNode); // path = dijkstra.Path; }
private double[][] initShortPathCost(List<MazeSpaceNodesArea> roomToSerch, Dijkstras.Graph graph) { double[][] shortPathCostTemp = new double[roomToSerch.Count][]; for (int i = 0; i < shortPathCostTemp.Length; i++) shortPathCostTemp[i] = new double[shortPathCostTemp.Length]; MazeSpaceNodesArea tempStart,tempEnd; for (int i = 0; i < roomToSerch.Count; i++) { tempStart = roomToSerch[i] as MazeSpaceNodesArea; for (int j = 0; j < roomToSerch.Count; j++) { tempEnd = roomToSerch[j] as MazeSpaceNodesArea; shortPathCostTemp[i][j] = graph.SumShortestPathConst(tempStart.NodeId,tempEnd.NodeId); } } return shortPathCostTemp; }
void Start() { djk = GetComponent <Dijkstras>(); options.GetComponent <GraphicRaycaster>().enabled = false; }
public void GatherStats() { avgPassageLength = 0; longestPassage = 0; intersections = 0; float passageLength; Cell current; bool[,] visited = new bool[width, height]; List <float> passageLengths = new List <float>(); List <float> store = new List <float>(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (cellArray[i, j].numLinks == 1) { // number of dead ends numDeadEnds++; // passage lengths passageLength = 1; current = cellArray[i, j]; visited[i, j] = true; while (current.numLinks <= 2) { foreach (Cell c in current.neighbours) { if (c != null) { if (current.Linked(c) && !visited[c.x, c.y] && c.numLinks <= 2) { current = c; passageLength++; visited[current.x, current.y] = true; break; } else if (c.numLinks > 2) { current = c; break; } } } } passageLengths.Add(passageLength); // longest passage if (passageLength > longestPassage) { longestPassage = (int)passageLength; } // avg passage length if (avgPassageLength == 0) { avgPassageLength = passageLength; } else { avgPassageLength = (avgPassageLength + passageLength) / 2f; } } // intersections else if (cellArray[i, j].numLinks >= 3) { intersections++; } } } // standard deviation foreach (float p in passageLengths) { store.Add((p - passageLengths.Average()) * (p - passageLengths.Average())); } stdDevPassageLength = Mathf.Sqrt(store.Sum() / store.Count); // distance array Dijkstras dijkstras = new Dijkstras(this); distances = dijkstras.Distances(); maxDistance = dijkstras.maxDistance; }