public string Solve() { var d = new Dijkstra(graph); graph = d.Calculate(); SelectResult(graph); return result.Max(g => g.PathLength).ToString(CultureInfo.InvariantCulture); }
public void ShouldFindShortesPathWhen1PathExists() { //http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm var one = new GraphNode<int>(1); var two = new GraphNode<int>(2); var three = new GraphNode<int>(3); var four = new GraphNode<int>(4); var five = new GraphNode<int>(5); var six = new GraphNode<int>(6); one.AddNeighbour(six, 14); one.AddNeighbour(three, 9); one.AddNeighbour(two, 7); two.AddNeighbour(three, 10); two.AddNeighbour(four, 15); three.AddNeighbour(six, 2); three.AddNeighbour(four, 11); four.AddNeighbour(five, 6); five.AddNeighbour(six, 9); var graph = new List<GraphNode<int>> {one, two, three, four, five, six}; var dijkstra = new Dijkstra<int>(graph); var path = dijkstra.FindShortestPathBetween(one, five); path[0].Value.ShouldBe(1); path[1].Value.ShouldBe(3); path[2].Value.ShouldBe(6); path[3].Value.ShouldBe(5); }
public void NoPath() { var dk = new Dijkstra(); dk.AddPath(0, 1, 1); dk.AddPath(2, 3, 1); dk.AddPath(3, 4, 1); dk.AddPath(4, 5, 1); Assert.AreEqual(Int32.MaxValue, dk.GetMinCost(0)[5]); }
public override double DistanceTo(Dijkstra.Node neighbour) { var node2 = neighbour as Address; var x = radians(node2.Longitude - this.Longitude) * Math.Cos(radians(this.Latitude + node2.Latitude) / 2); var y = radians(node2.Latitude - this.Latitude); var d = Math.Sqrt(x * x + y * y) * 6371; return d; }
public void EdgeCase() { var dk = new Dijkstra(); dk.AddPath(0, 1, 1); dk.AddPath(1, 2, 1); dk.AddPath(2, 3, 1); dk.AddPath(3, 4, 1); Assert.AreEqual(4, dk.GetMinCost(0)[4]); dk = new Dijkstra(); dk.AddPath(0, 1, 1); Assert.AreEqual(1, dk.GetMinCost(0)[1]); }
public void Ordinal() { var dk = new Dijkstra(); dk.AddPath(0, 1, 3); dk.AddPath(0, 2, 1); dk.AddPath(1, 2, 2); dk.AddPath(1, 3, 1); dk.AddPath(1, 4, 2); dk.AddPath(2, 1, 1); dk.AddPath(2, 4, 4); dk.AddPath(3, 2, 2); dk.AddPath(3, 4, 4); Assert.AreEqual(4, dk.GetMinCost(0)[4]); }
private List <Indice> AttackRangeOfUnitAtPosition(Unit unit, Indice position) { List <Indice> tiles; switch (unit.UnitClass) { case UnitClass.Figher: tiles = Dijkstra.TilesWithinDistanceRange(this, position, MovementType.Attack, 1, 1); break; case UnitClass.Archer: tiles = Dijkstra.TilesWithinDistanceRange(this, position, MovementType.Attack, 2, 3); break; default: tiles = new List <Indice>(); break; } return(tiles); }
public void GivenDeadEnd_ExpectDistance2() { // A -> B // | // v // C -> D var vertexA = new GraphVertex("A"); var vertexB = new GraphVertex("B"); var vertexC = new GraphVertex("C"); var vertexD = new GraphVertex("D"); vertexA.AddConnectionToVertex(vertexB); vertexA.AddConnectionToVertex(vertexC); vertexC.AddConnectionToVertex(vertexD); var solution = Dijkstra.Solve(vertexA, vertexD); solution.Should().Be(2); }
public ShortestResponse GetShortestPath(SearchReq request) { MethodBase currentMethod = MethodBase.GetCurrentMethod(); try { Dijkstra dijkstra = new Dijkstra(); dijkstra.ShortestPath(request.source, request.destination); var response = new ShortestResponse(); response.Stations = new List <Stations>(); response.Stations = dijkstra.stations; response.Routepath = dijkstra.routpath; response.Cost = dijkstra.Cost; return(response); } catch (Exception ex) { AirlineLogManager.Error(null, CurrentClass, currentMethod, ex); } return(null); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testDijkstraDirection3() public virtual void TestDijkstraDirection3() { Relationship r1 = Graph.makeEdge("start", "b"); Relationship r2 = Graph.makeEdge("c", "b"); Relationship r3 = Graph.makeEdge("c", "d"); Relationship r4 = Graph.makeEdge("e", "d"); Relationship r5 = Graph.makeEdge("e", "f"); Relationship r6 = Graph.makeEdge("g", "f"); Relationship r7 = Graph.makeEdge("g", "end"); Dictionary <Relationship, Direction> dirs = new Dictionary <Relationship, Direction>(); Dijkstra <double> dijkstra = new Dijkstra <double>(( double )0, Graph.getNode("start"), Graph.getNode("end"), new directionSavingCostEvaluator(this, dirs), new Org.Neo4j.Graphalgo.impl.util.DoubleAdder(), double?.compareTo, Direction.BOTH, MyRelTypes.R1); dijkstra.Cost; assertEquals(Direction.OUTGOING, dirs[r1]); assertEquals(Direction.INCOMING, dirs[r2]); assertEquals(Direction.OUTGOING, dirs[r3]); assertEquals(Direction.INCOMING, dirs[r4]); assertEquals(Direction.OUTGOING, dirs[r5]); assertEquals(Direction.INCOMING, dirs[r6]); assertEquals(Direction.OUTGOING, dirs[r7]); }
public Dictionary <uint, int> GetDistanceToTag(Tag tag) { List <Node> nodesWithTag = GetNodesWithTag(tag); if (nodesWithTag.Count > 0) { Dijkstra dijkstra = new Dijkstra(baseGraph, (Satsuma.Arc arc) => 1.0, DijkstraMode.Sum); for (int i = 0; i < nodesWithTag.Count; i++) { dijkstra.AddSource(nodesWithTag[i].node); } Dictionary <uint, int> dictionary = new Dictionary <uint, int>(); for (int j = 0; j < nodes.Count; j++) { dijkstra.RunUntilFixed(nodes[j].node); dictionary[(uint)nodes[j].node.Id] = (int)dijkstra.GetDistance(nodes[j].node); } return(dictionary); } return(null); }
/// <summary> /// Test case for a path of length zero, with some surrounding nodes /// </summary> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testDijkstraMinimal2() public virtual void TestDijkstraMinimal2() { Graph.makeEdge("a", "b", "cost", ( double )1); Graph.makeEdge("a", "c", "cost", ( float )1); Graph.makeEdge("a", "d", "cost", ( long )1); Graph.makeEdge("a", "e", "cost", 1); Graph.makeEdge("b", "c", "cost", ( sbyte )1); Graph.makeEdge("c", "d", "cost", ( short )1); Graph.makeEdge("d", "e", "cost", ( double )1); Graph.makeEdge("e", "f", "cost", ( double )1); Dijkstra <double> dijkstra = GetDijkstra(Graph, 0.0, "a", "a"); assertEquals(0.0, dijkstra.Cost, 0.0); assertEquals(1, dijkstra.PathAsNodes.Count); dijkstra = GetDijkstra(Graph, 3.0, "a", "a"); assertEquals(6.0, dijkstra.Cost, 0.0); assertEquals(1, dijkstra.PathAsNodes.Count); assertEquals(0, dijkstra.PathAsRelationships.Count); assertEquals(1, dijkstra.Path.Count); assertEquals(1, dijkstra.PathsAsNodes.Count); }
public void AlgorithmExitsWithEmptyGraph() { //Arrange /** * Create the below matrix * [-1][-1] * [-1][-1] **/ int[][] m = Matrix.Create(2, 2); int[] expectedOutput = new int[2] { 0, -1 }; //Act int[] actualOutput = Dijkstra.FindShortestPaths(m, 0, 0).PathLengths; //Assert Assert.AreEqual(expectedOutput, actualOutput); }
private void AddSupernodeGrid(int gridSize, Vector3I size) { for (var dX = Math.Min(gridSize / 2, size[0]); dX <= size[0]; dX += gridSize) { for (var dY = Math.Min(gridSize / 2, size[1]); dY <= size[1]; dY += gridSize) { for (var dZ = Math.Min(gridSize / 2, size[2]); dZ <= size[2]; dZ += gridSize) { var node = _grid.GetNearestItem(new Vector3I(dX, dY, dZ), 5); if (node == null) { continue; } var supernode = new SuperNode(node.Position, gridSize); _gridT1[dX, dY, dZ] = supernode; Dijkstra.Fill(GetNode(supernode.Position), gridSize, supernode); } } } }
private void TestWeightedGraph() { WeightedGraph grafoValorado = new WeightedGraph(5, false); grafoValorado.nuevoVertex("A"); grafoValorado.nuevoVertex("B"); grafoValorado.nuevoVertex("C"); grafoValorado.nuevoVertex("D"); grafoValorado.nuevoVertex("E"); grafoValorado.nuevoArco("A", "B", 1); grafoValorado.nuevoArco("B", "C", 2); grafoValorado.nuevoArco("B", "D", 2); grafoValorado.nuevoArco("A", "C", 1); grafoValorado.nuevoArco("D", "E", 10); Debug.Log(grafoValorado.ToString()); Dijkstra caminoCorto = new Dijkstra(); string[] camino = caminoCorto.FindPath(grafoValorado, "A", "E"); Debug.Log("Camino :" + string.Join("-> ", camino)); }
public override void BeforeMove(GameState gameState) { base.BeforeMove(gameState); if (TargetZone != null && !isValidTarget(gameState, TargetZone)) { TargetZone = null; } if (TargetZone == null) { //Log("EdgeFinder at #{0} needs to determine where to go.", ZoneId); var bfs = new Dijkstra(gameState.Zones, this.ZoneId); //Try to move to the closest unexplored area var possibleTargets = gameState.Zones .Where(zone => isValidTarget(gameState, zone)) .ToArray(); var target = closestTargetOf(bfs, possibleTargets); //... and secondary to the closest active MazeRunner if (target == null) { possibleTargets = gameState.Squads.OfType <MazeRunner>().Select(x => gameState.Zones[x.ZoneId]).ToArray(); target = closestTargetOf(bfs, possibleTargets); } if (target == null) { #warning What if we can't find a valid target? Log("EdgeFinder at zone #{0} could not find a valid target. Idling.", this.ZoneId); } else { TargetZone = target.Item1; _path = new Queue <int>(target.Item2.Skip(1)); Log("EdgeFinder at zone #{0} is heading for zone #{1} through path {2}", this.ZoneId, this.TargetZone.Id, string.Join(", ", _path.ToArray())); } } }
private void RunAlgorithm(string _algoName, Graph _graph) { // Variables DateTime beginning; DateTime end; TimeSpan duration; Algorithm algo = null; // Création de l'algorithme switch (_algoName) { case "Depth-First": algo = new DepthFirst(_graph, this); // Algorithm(Graph _graph, IHM _ihm). break; case "Breadth-First": algo = new BreadthFirst(_graph, this); break; case "Bellman-Ford": algo = new BellmanFord(_graph, this); break; case "Dijkstra": algo = new Dijkstra(_graph, this); break; case "A*": algo = new AStar(_graph, this); break; } // Résolution Console.Out.WriteLine("Algorithme : " + _algoName); beginning = DateTime.Now; algo.Solve(); end = DateTime.Now; duration = end - beginning; Console.Out.WriteLine("Durée (ms) : " + duration.TotalMilliseconds.ToString() + "\n"); }
public static void CompareAlgorithms(string outputDirectory) { //pick random start point var rnd = new Random(); ulong startId = SvgHelper.Dictionary.Keys.ElementAt(rnd.Next(SvgHelper.Dictionary.Count)); var(distD, pD) = TimeHelper.MeasureTimeAlgorithm(() => Dijkstra.Calculate(startId), "Dijkstra"); var(distL, pL) = TimeHelper.MeasureTimeAlgorithm(() => Levit.Calculate(startId), "Levit"); //var timeD = new List<long>(); //var timeL = new List<long>(); //for (int i = 0; i < 100; i++) //{ // ulong startId = SvgHelper.Dictionary.Keys.ElementAt(rnd.Next(SvgHelper.Dictionary.Count)); // var tD = Stopwatch.StartNew(); // var (distD, pD) = Dijkstra.Calculate(startId);// TimeHelper.MeasureTimeAlgorithm(() => Dijkstra.Calculate(startId), "Dijkstra"); // timeD.Add(tD.ElapsedTicks); // var tL = Stopwatch.StartNew(); // var (distL, pL) = // Levit.Calculate( // startId); //TimeHelper.MeasureTimeAlgorithm(() => Levit.Calculate(startId), "Levit"); // timeL.Add(tL.ElapsedTicks); //} //Console.WriteLine($"timing information:\tsum - {new TimeSpan(timeD.Sum())}\t max - {new TimeSpan(timeD.Max())}\t avg - {new TimeSpan(Convert.ToInt64(timeD.Average()))}"); //Console.WriteLine($"timing information:\tsum - {new TimeSpan(timeL.Sum())}\t max - {new TimeSpan(timeL.Max())}\t avg - {new TimeSpan(Convert.ToInt64(timeL.Average()))}"); // compare Dijkstra and Levit var differences = distL.Values.Zip(distD.Values, (d, l) => Math.Abs(d - l)).ToList(); Console.WriteLine("Compare results for Dijkstra and Levit algorithms:"); Console.WriteLine($"Difference between distances:\t sum - {differences.Sum()}\t max - {differences.Max()}\t avg - {differences.Average()}"); Console.WriteLine($"Ancestors lists are {(pD.OrderBy(x => x.Key).SequenceEqual(pL.OrderBy(x => x.Key)) ? "equal" : "not equal")}"); TimeHelper.MeasureTime(() => CsvHelper.WriteShortestPathes(outputDirectory, startId, Destinations.Keys.OrderBy(x => distD[x]), distD, pD), "writing shortest pathes to csv"); TimeHelper.MeasureTime(() => SvgHelper.DisplayShortestPathes(outputDirectory, startId, Destinations.Keys.OrderBy(x => distD[x]), pD), "writing shortest pathes to svg"); var heuristicsFunctions = new Dictionary <Func <GeoPoint, GeoPoint, double>, (List <double> differences, List <long> timings)> {
void Start() { LINKS = GameObject.Find("LinkList").GetComponent <LinkList>(); dijkstra = new Dijkstra(); goalPointMaster = new GoalPointMaster(); StartPoint = new DijkstraNode(StartX, StartY); //一番近いゴール地点を探すメソッドを呼び出す GoalPoint = goalPointMaster.Calculate_SG_Distance(StartPoint); //最短経路探索実行 result = dijkstra.Execute(StartPoint, GoalPoint); RouteList = dijkstra.FindRoute(); //経路を取得 for (int j = 0; j < RouteList.Count; j++) { linkChanger.Add(RouteList[j].linkID); } linkIDs = linkChanger.ToArray(); timer = GameObject.Find("Timer").GetComponent <Timer>(); dTime = timer.dTime; foreach (string i in linkIDs) { linklist.Add(LINKS.linkList[i]); } nowLink = linklist[nowLinkIndex]; //carListはリンク上にいる車の台数や名前等を持つリスト nowLink.carList.Add(this); nodes = nowLink.getStartNodes(transform.position.x, transform.position.y, carName); rect = nowLink.getRect(nodes[0], nodes[1]); endNodeDis = nowLink.length - runDistance; startTime = timer.Time; }
public void LoadMap(int[,] map) { this.mapSize = map.GetLength(0); this.map = (int[, ])map.Clone(); ParseMapdata(); // Debugging Code // Print Dijkstra Weight graph int i = 0; string report = ""; foreach (int weight in weightGraph) { report += weight + " "; if ((++i % weightGraph.GetLength(0)) == 0) { report += "\n"; } } Debug.Log(report); // Print Vertex coords Array report = ""; foreach (Coord crd in vertexes.Keys) { report += crd.ToString() + " " + vertexes[crd] + "\n"; } Debug.Log(report); // Print Dijkstra result from vertex 0 report = ""; ArrayList list = Dijkstra.dijkstra(weightGraph, 0); foreach (int ver in list) { report += ver + " "; } Debug.Log(report); }
//interface public static void Configure(XmlNode configuration) { XmlNode bundle = configuration[Bundle.BundleTag]; if (bundle != null) { Bundle.Configure(bundle); } XmlNode ip = configuration[Ip.IpTag]; if (ip != null) { Ip.Configure(ip); } XmlNode linkLayer = configuration[LinkLayer.LinLayerTag]; if (linkLayer != null) { LinkLayer.Configure(linkLayer); } XmlNode udp = configuration[Udp.UdpTag]; if (udp != null) { Udp.Configure(udp); } XmlNode dijkstra = configuration[Dijkstra.DijkstraTag]; if (dijkstra != null) { Dijkstra.Configure(dijkstra); } XmlNode aodv = configuration[Aodv.AodvTag]; if (aodv != null) { Aodv.Configure(aodv); } }
public void SearchTest() { var graph = GetGraph(); var vertex0 = graph[0]; var vertex1 = graph[1]; var vertex2 = graph[2]; var vertex3 = graph[3]; var vertex4 = graph[4]; var vertex5 = graph[5]; var distances = Dijkstra.Search(graph, vertex0); var isValid = distances.FirstOrDefault(d => d.Vertex.Equals(vertex0)).Value == 0; isValid &= distances.FirstOrDefault(d => d.Vertex.Equals(vertex1)).Value == 7; isValid &= distances.FirstOrDefault(d => d.Vertex.Equals(vertex2)).Value == 9; isValid &= distances.FirstOrDefault(d => d.Vertex.Equals(vertex3)).Value == 20; isValid &= distances.FirstOrDefault(d => d.Vertex.Equals(vertex4)).Value == 20; isValid &= distances.FirstOrDefault(d => d.Vertex.Equals(vertex5)).Value == 11; Assert.IsTrue(isValid, "Distance not found correctly"); }
public void Teste_Caminho() { //arrange: string pastaArquivo = @"C:\Trabalho\TestePromob\JSONs"; string nomeArquivo = "Grafo1.json"; Grafo grafo = new Grafo(false, pastaArquivo + @"\" + nomeArquivo); string origem = "A"; string destino = "C"; Dijkstra dijkstra = new Dijkstra(); dijkstra.Monta(grafo, origem); string dist = "30"; //act: Caminho caminho = new Caminho(); List <string> listaCaminho = caminho.calcula_caminho(grafo.get_vertice(destino)); //assert: Assert.IsNotNull(listaCaminho); Assert.AreEqual(grafo.get_vertice(destino).get_distancia().ToString("0"), "30"); }
private void btnDijkstra_Click(object sender, EventArgs e) { nodoDijkstra = new NodoDijkstra(); nodoDijkstra.cmbNodoDijkstra.Items.AddRange(grafo.ArregloNodos()); nodoDijkstra.ShowDialog(); if(nodoDijkstra.control) { //MessageBox.Show(nodoDijkstra.cmbNodoDijkstra.SelectedIndex.ToString()); string miCadena = String.Empty; algoritmoDijkstra = new Dijkstra(grafo, nodoDijkstra.cmbNodoDijkstra.SelectedIndex); MessageBox.Show(algoritmoDijkstra.CorrerDijkstra(grafo)); miCadena = "La solucion de la ruta mas corta tomando como nodo inicial el NODO " + nodoDijkstra.cmbNodoDijkstra.Text + " es: \n"; int nodos = 0; foreach (int i in algoritmoDijkstra.D) { miCadena += "Distancia minima a nodo " + grafo.ArregloDeNodos()[nodos].ToString() + " es: " + i + "\n"; nodos++; } MessageBox.Show(miCadena); } algoritmoDijkstra = null; }
public override IEnumerable <object> Solve(TextReader inputStream) { const long startYen = 1_000_000_000_000_000; var(citiesCount, trainsCount, start, terminal) = inputStream.ReadValue <int, int, int, int>(); start--; terminal--; var yenGraph = new WeightedGraph(citiesCount); var snuukGraph = new WeightedGraph(citiesCount); for (int i = 0; i < trainsCount; i++) { var(from, to, yen, snuuk) = inputStream.ReadValue <int, int, long, long>(); from--; to--; yenGraph.AddEdge(new WeightedEdge(from, to, yen)); yenGraph.AddEdge(new WeightedEdge(to, from, yen)); snuukGraph.AddEdge(new WeightedEdge(from, to, snuuk)); snuukGraph.AddEdge(new WeightedEdge(to, from, snuuk)); } var yenFares = new Dijkstra <BasicNode, WeightedEdge>(yenGraph).GetDistancesFrom(new BasicNode(start)); var snuukFares = new Dijkstra <BasicNode, WeightedEdge>(snuukGraph).GetDistancesFrom(new BasicNode(terminal)); var remainedSnuuks = new Stack <long>(citiesCount); for (int exchange = citiesCount - 1; exchange >= 0; exchange--) { var best = remainedSnuuks.Count > 0 ? remainedSnuuks.Peek() : int.MinValue; var next = startYen - (yenFares[exchange] + snuukFares[exchange]); remainedSnuuks.Push(Math.Max(best, next)); } foreach (var remainedSnuuk in remainedSnuuks) { yield return(remainedSnuuk); } }
public void Graf_Dijkstra_Ok() { var g = new Graph(); var pointA = new MapPoint(1, 1, "A"); var pointB = new MapPoint(2, 2, "B"); var pointC = new MapPoint(3, 3, "C"); var pointD = new MapPoint(4, 4, "D"); var pointE = new MapPoint(5, 5, "E"); var pointF = new MapPoint(6, 6, "F"); var pointG = new MapPoint(7, 7, "G"); //добавление вершин var vertexA = g.AddVertex(pointA); var vertexB = g.AddVertex(pointB); var vertexC = g.AddVertex(pointC); var vertexD = g.AddVertex(pointD); var vertexE = g.AddVertex(pointE); var vertexF = g.AddVertex(pointF); var vertexG = g.AddVertex(pointG); //добавление ребер g.AddEdge(pointA, pointB, 22); g.AddEdge(pointA, pointC, 33); g.AddEdge(pointA, pointD, 61); g.AddEdge(pointB, pointC, 47); g.AddEdge(pointB, pointE, 93); g.AddEdge(pointC, pointD, 11); g.AddEdge(pointC, pointE, 79); g.AddEdge(pointC, pointF, 63); g.AddEdge(pointD, pointF, 41); g.AddEdge(pointE, pointF, 17); g.AddEdge(pointE, pointG, 58); g.AddEdge(pointF, pointG, 84); var dijkstra = new Dijkstra(g); var path = dijkstra.FindShortestPath(vertexA, vertexG); var pointList = dijkstra.FindShortestPointListPath(vertexA, vertexG); }
private List <ACommand> GetValidMoviments() { List <ACommand> validMvs = new List <ACommand>(); foreach (APawn pawn in CurPlayer.GetPawns()) { Dijkstra didi = new Dijkstra(Boards.GetBoard(), pawn.Position, pawn.MovePoints); List <Coord> moveRange = didi.GetValidPaths(Command.MOVE); foreach (Coord cell in moveRange) { MoveCommand mv = new MoveCommand(); mv.SetUp(Boards, CurPlayer, GetOponent()); mv.SetUp(CurPlayer, pawn.Position, cell, Boards); if (mv.IsValid()) { validMvs.Add(mv); } } } return(validMvs); }
/// <summary> /// Move the ghost to the entrance of the maze /// </summary> /// <returns></returns> public Direction?MoveToStart() { Dijkstra dijkstra = new Dijkstra(GhostManager.Instance.Map); Direction?direction = dijkstra.ComputeDirection( // Start: Current ghost position ConvertPositionToTileIndexes(), // Destination: Pac's position ConvertPositionToTileIndexes(StartingPoint)); if (direction != null) { //MoveToDirection((Direction)direction); return(direction); } // Else, if the ghost arrives else { State = GhostState.RUNNING; } return(null); }
/** 計算。 * * return == true : 継続。 * */ public bool Calc(Fee.Dijkstra.Instance_Base a_instance) { //到達コストが最小のノードを検索。 Node <NODEKEY, NODEDATA, LINKDATA> t_node_current = Dijkstra <NODEKEY, NODEDATA, LINKDATA> .FindMinCostNode(a_instance, this.calc_list); if (t_node_current == null) { return(false); } else { //未計算リストから削除。 this.calc_list.Remove(t_node_current); t_node_current.SetCalcFlag(a_instance, false); } //隣接ノード計算開始。 System.Collections.Generic.List <Link <NODEKEY, NODEDATA, LINKDATA> > t_linklist_current = t_node_current.GetLinkList(); for (int ii = 0; ii < t_linklist_current.Count; ii++) { Node <NODEKEY, NODEDATA, LINKDATA> t_node = t_linklist_current[ii].GetToNode(); long t_total_cost = t_node_current.GetTotalCost(a_instance) + t_linklist_current[ii].GetToCost(a_instance); if ((t_node.GetTotalCost(a_instance) < 0) || (t_node.GetTotalCost(a_instance) > t_total_cost)) { //このノードへ到達するための隣接ノード。 t_node.SetTotalCost(a_instance, t_total_cost); t_node.SetPrevNode(t_node_current); //計算リストに追加。 if (t_node.GetCalcFlag(a_instance) == false) { this.calc_list.Add(t_node); t_node.SetCalcFlag(a_instance, true); } } } return(true); }
public void TestInitializeGraph() { var program = new Dijkstra(); var list = new List <Tuple <string, string, int> > { new Tuple <string, string, int>("aa", "bb", 1), new Tuple <string, string, int>("cc", "dd", 2), new Tuple <string, string, int>("aa", "ff", 3), new Tuple <string, string, int>("bb", "aa", 4) }; var verteces = program.InitVerteces(list).OrderBy(x => x.Value).ToArray(); (verteces.Distinct().Count() == verteces.Length).Should().BeTrue(); verteces.Length.Should().Be(5); verteces[0].Value.Should().Be("aa"); verteces[1].Value.Should().Be("bb"); verteces[2].Value.Should().Be("cc"); verteces[3].Value.Should().Be("dd"); verteces[4].Value.Should().Be("ff"); }
public void TestMethod1() { IGraph graph1 = new AdjacencyMatrixGraph(4, GraphType.DIRECTED); graph1.AddEdge(0, 1, 4); graph1.AddEdge(1, 2, 4); graph1.AddEdge(0, 3, 1); graph1.AddEdge(3, 2, 1); Dijkstra.ShortestPath(graph1, 0, 2); graph1 = new AdjacencyMatrixGraph(8, GraphType.DIRECTED); graph1.AddEdge(2, 7, 4); graph1.AddEdge(0, 3, 2); graph1.AddEdge(0, 4, 2); graph1.AddEdge(0, 1, 1); graph1.AddEdge(2, 1, 3); graph1.AddEdge(1, 3, 2); graph1.AddEdge(3, 5, 1); graph1.AddEdge(3, 6, 3); graph1.AddEdge(4, 7, 2); graph1.AddEdge(7, 5, 4); Dijkstra.ShortestPath(graph1, 0, 5); //Console.WriteLine("------------------------------"); graph1 = new AdjacencyMatrixGraph(4, GraphType.DIRECTED); graph1.AddEdge(0, 3, 20); graph1.AddEdge(0, 2, 3); graph1.AddEdge(0, 1, 24); graph1.AddEdge(2, 3, 12); Dijkstra.ShortestPath(graph1, 0, 1); Dijkstra.ShortestPath(graph1, 0, 2); Dijkstra.ShortestPath(graph1, 0, 3); }
public void TestShortestWay() { Graph graph = new Graph(5); graph.AddBidirectionnalLink(0, 1); graph.AddBidirectionnalLink(1, 2); graph.AddBidirectionnalLink(2, 3); graph.AddBidirectionnalLink(3, 4); graph.AddBidirectionnalLink(0, 4); int dist; var result = Dijkstra.Calculate(graph, 0, 4); List <int> expectedResult = new List <int>(); expectedResult.Add(4); Assert.AreEqual(1, result.Dist); for (int i = 0; i < expectedResult.Count; i++) { Assert.AreEqual(expectedResult[i], result.Path[i]); } }
static void Main(string[] args) { var dijkstra = new Dijkstra(DistanceMatrix); for (int i = 0; i < 10; i++) { for (int j = i; j < 10; j++) { var path = dijkstra.GetShortestPath(i, j); // print complex paths that are shorter than just going straight there... if (path.Count > 2) { Console.Write("From {0} to {1}: ", i,j); foreach (var item in path) { Console.Write(" {0} ", item.index); } Console.WriteLine(": Total distance: {0}, Direct distance: {1}", path.Last().distanceFromStart, DistanceMatrix[i,j]); } } } }
private void GetPreciseRegionLinkDistances(WaterRegion region, CellRect destination, List <Pair <WaterRegionLink, int> > outDistances) { outDistances.Clear(); RegionCostCalculatorShips.tmpCellIndices.Clear(); if (destination.Width == 1 && destination.Height == 1) { RegionCostCalculatorShips.tmpCellIndices.Add(this.map.cellIndices.CellToIndex(destination.CenterCell)); } else { CellRect.CellRectIterator iterator = destination.GetIterator(); while (!iterator.Done()) { IntVec3 c = iterator.Current; if (c.InBoundsShip(this.map)) { RegionCostCalculatorShips.tmpCellIndices.Add(this.map.cellIndices.CellToIndex(c)); } iterator.MoveNext(); } } Dijkstra <int> .Run(RegionCostCalculatorShips.tmpCellIndices, (int x) => this.PreciseRegionLinkDistancesNeighborsGetter(x, region), this.preciseRegionLinkDistancesDistanceGetter, RegionCostCalculatorShips.tmpDistances, null); foreach (WaterRegionLink regionLink in region.links) { if (regionLink.GetOtherRegion(region).Allows(this.traverseParms, false)) { float num; if (!RegionCostCalculatorShips.tmpDistances.TryGetValue(this.map.cellIndices.CellToIndex(this.linkTargetCells[regionLink]), out num)) { Log.ErrorOnce("Dijkstra couldn't reach one of the cells even though they are in the same region. There is most likely something wrong with the " + "neighbor nodes getter. Error occurred in ShipPathFinder of RimShips", 1938471531, false); num = 100f; } outDistances.Add(new Pair <WaterRegionLink, int>(regionLink, (int)num)); } } }
private void FillSupernodeHoles(int gridSize, Vector3I size, Vector3I startPosition) { for (var dX = startPosition.x; dX <= size[0]; dX++) { for (var dY = startPosition.y; dY <= size[1]; dY++) { for (var dZ = startPosition.z; dZ <= size[2]; dZ++) { var node = _grid[dX, dY, dZ]; if (node == null || node.SuperNodes.Count > 0) { continue; } var supernode = new SuperNode(node.Position, gridSize); _gridT1[dX, dY, dZ] = supernode; Dijkstra.Fill(GetNode(supernode.Position), gridSize, supernode); } } } return; }
public void ReturnShortestDijkstraRouteTest(int totalLoc) { int totalLocations = totalLoc; if (totalLoc < 2) { totalLocations = rgn.Next(2, 11); } List <Location> locations = new List <Location>(); List <Road> roads = new List <Road>(); for (int i = 0; i < totalLocations; i++) { Location temp = new Location(2, rgn.Next(0, 100), rgn.Next(0, 100)); locations.Add(temp); } for (int i = 0; i < locations.Count - 1; i++) { Road temp = new Road(locations[i], locations[i + 1]); temp.InitialCost = rgn.Next(1, 4); roads.Add(temp); } int randomRoadsCount = (int)Math.Floor((double)totalLocations / 2); for (int i = 1; i <= randomRoadsCount; i++) { int num1 = rgn.Next(0, randomRoadsCount); int num2 = rgn.Next(randomRoadsCount, totalLocations); Road temp = new Road(locations[num1], locations[num2]); temp.InitialCost = rgn.Next(50, 100); roads.Add(temp); } Dijkstra d = new Dijkstra(roads); DijkstraRoute dr = d.GetRouteTo(locations[0], locations[totalLocations - 1]); Assert.True(dr.RouteLenght < 50); }
private void GetPreciseRegionLinkDistances(Region region, CellRect destination, List <Pair <RegionLink, int> > outDistances) { outDistances.Clear(); RegionCostCalculator.tmpCellIndices.Clear(); if (destination.Width == 1 && destination.Height == 1) { RegionCostCalculator.tmpCellIndices.Add(this.map.cellIndices.CellToIndex(destination.CenterCell)); } else { CellRect.CellRectIterator iterator = destination.GetIterator(); while (!iterator.Done()) { IntVec3 current = iterator.Current; if (current.InBounds(this.map)) { RegionCostCalculator.tmpCellIndices.Add(this.map.cellIndices.CellToIndex(current)); } iterator.MoveNext(); } } Dijkstra <int> .Run(RegionCostCalculator.tmpCellIndices, (int x) => this.PreciseRegionLinkDistancesNeighborsGetter(x, region), this.preciseRegionLinkDistancesDistanceGetter, RegionCostCalculator.tmpDistances, null); for (int i = 0; i < region.links.Count; i++) { RegionLink regionLink = region.links[i]; if (regionLink.GetOtherRegion(region).type.Passable()) { float num; if (!RegionCostCalculator.tmpDistances.TryGetValue(this.map.cellIndices.CellToIndex(this.linkTargetCells[regionLink]), out num)) { Log.ErrorOnce("Dijkstra couldn't reach one of the cells even though they are in the same region. There is most likely something wrong with the neighbor nodes getter.", 1938471531); num = 100f; } outDistances.Add(new Pair <RegionLink, int>(regionLink, (int)num)); } } }
public void CreateSolver(AlgorithmType algoType, IIndexedPathfindingMap map, double heuristic, out IPathFinder<Vector2i> pathFinder, out IPathFindingListener<Vector2i> listener) { switch (algoType) { case AlgorithmType.AStar: listener = new AStarListener(); pathFinder = new AStar<Vector2i>(map.GetNeighbors, map.DistanceEstimate, heuristic) { Listener = (IAStarListener<Vector2i>)listener }; return; case AlgorithmType.Dijkstra: listener = new DijkstraListener(); pathFinder = new Dijkstra<Vector2i>(map.GetNeighbors, map.DistanceEstimate) { Listener = listener }; return; } throw new Exception($"Unrecognized algorithm type: {algoType}"); }
private static int shortestDistanceFor(int[] playerIndexes, Dijkstra[] paths, Dijkstra.Node tile) { //Player.Debug("Indexes: {0}", string.Join(", ", playerIndexes)); //Player.Debug("Paths: {0}", paths.Length); var length = playerIndexes .Where(index => paths[index].Path != null) .ToArray(); length = length .Where(index => paths[index].Path.ContainsKey(tile.Id)) .ToArray(); length = length .Select(index => paths[index].Path[tile.Id]) .Where(path => path != null) .Select(path => path.Length) .ToArray(); if (length == null || length.Length == 0) return int.MaxValue; return length .DefaultIfEmpty(int.MaxValue) .Min(); }
static void Main(string[] args) { string startPoint = Console.ReadLine().Substring(9); string endPoint = Console.ReadLine().Substring(9); int N = int.Parse(Console.ReadLine()); var addresses = new Address[N]; for (int i = 0; i < N; i++) { string stopName = Console.ReadLine(); addresses[i] = new Address(stopName); } int M = int.Parse(Console.ReadLine()); var links = new Link[M]; for (int i = 0; i < M; i++) { string route = Console.ReadLine(); var nodes = route.Split(new[] { ' ' }, 2).Select(x => x.Substring(9)).ToArray(); links[i] = new Link { A = nodes[0], B = nodes[1] }; } build(links, addresses); var bfs = new Dijkstra(addresses, startPoint); var path = bfs.Path(endPoint); if (path == null) { Console.WriteLine("IMPOSSIBLE"); } else { var addressDictionary = addresses.ToDictionary(x => x.Id); foreach (var stopArea in path) { var address = addressDictionary[stopArea]; Console.WriteLine(address.Fullname); } } }
static void Main(string[] args) { //Console.Error.WriteLine("Number of Nodes, Links, Gateways"); string[] inputs; inputs = Console.ReadLine().Split(' '); //Console.Error.WriteLine(string.Join(" ", inputs)); int N = int.Parse(inputs[0]); // the total number of nodes in the level, including the gateways int L = int.Parse(inputs[1]); // the number of links int E = int.Parse(inputs[2]); // the number of exit gateways //Console.Error.WriteLine("All links, one per line"); var links = new List<Link>(); for (int i = 0; i < L; i++) { inputs = Console.ReadLine().Split(' '); //Console.Error.WriteLine(string.Join(" ", inputs)); links.Add(new Link { A = inputs[0], B = inputs[1] }); } //Console.Error.WriteLine("All gateway node indexes, one per line"); var gateways = new string[E]; for (int i = 0; i < E; i++) { gateways[i] = Console.ReadLine(); // the index of a gateway node //Console.Error.WriteLine(gateways[i]); } // game loop while (true) { //Console.Error.WriteLine("Current SI position"); var SI = Console.ReadLine(); // The index of the node on which the Skynet agent is positioned this turn //Console.Error.WriteLine(SI); //Console.Error.WriteLine("\nINPUT READ."); var gatewayLinks = links.Where(link => gateways.Intersect(link.Nodes).Any()).ToArray(); var namesOfNodesToGateways = gatewayLinks.SelectMany(link => link.Nodes).Except(gateways).Distinct().ToArray(); //foreach (var node in nodesInFrontOfGateways) //{ // Console.Error.WriteLine(node + " is in front of one or more gateways"); //} var nodeToGateways = namesOfNodesToGateways.Select(node => new Node { Name = node, Links = links.Where(link => link.A == node && gateways.Contains(link.B) || link.B == node && gateways.Contains(link.A) ).ToArray(), Score = double.MaxValue }).ToArray(); foreach (var node in nodeToGateways) { var algorithm = new Dijkstra(links); node.Path = algorithm.Path(SI, node.Name); var pathNodesWithoutLinksToGateways = node.Path == null ? 0 : node.Path.Where(nodeName => !namesOfNodesToGateways.Contains(nodeName)).Count(); if (node.Path == null) { Console.Error.WriteLine("Node " + node + " has no path"); node.Score = 0; } else if (node.Links.Count() == 1) { //Console.Error.WriteLine("Node " + node.Name + " links to only one gateway"); node.Score = node.Path.Length == 1 ? double.MaxValue : 0;// 1.0 / node.Path.Length; } else { node.Score = pathNodesWithoutLinksToGateways == 0 ? double.MaxValue : (node.Links.Count() - 1) / (double)pathNodesWithoutLinksToGateways; } //Console.Error.WriteLine("Node " + node + " links to " + node.Links.Count() + " gateways, with " + pathNodesWithoutLinksToGateways + " chances to severe its links"); } foreach (var node in nodeToGateways.Where(node => node.Path != null).OrderByDescending(x => x.Score)) { var pathNodesWithoutLinksToGateways = node.Path == null ? 0 : node.Path.Where(nodeName => !namesOfNodesToGateways.Contains(nodeName)).Count(); Console.Error.WriteLine("Node " + node + " links to " + node.Links.Count() + " gateways, with " + pathNodesWithoutLinksToGateways + " chances to severe its links"); //Console.Error.WriteLine(node.Name + " is " + node.Path.Length + " steps away and has " + node.Links.Length + " gateway links => Score = " + node.Score); } if (nodeToGateways.Length == 0) { Console.Error.WriteLine("No gateways are reachable. I won!"); return; } var mostCriticalNode = nodeToGateways .Where(node => node.Path != null) .OrderByDescending(x => x.Score) .First(); var linkToSevere = mostCriticalNode.Links.First(); Console.WriteLine(linkToSevere); links.Remove(linkToSevere); } }
public void ShouldFindShortesPathWhen2PathExists() { //2 paths exist //O A B D T //O A B E D T // ReSharper disable InconsistentNaming var O = new GraphNode<string>("O"); var A = new GraphNode<string>("A"); var B = new GraphNode<string>("B"); var C = new GraphNode<string>("C"); var D = new GraphNode<string>("D"); var E = new GraphNode<string>("E"); var F = new GraphNode<string>("F"); var T = new GraphNode<string>("T"); // ReSharper restore InconsistentNaming O.AddNeighbour(A, 2); O.AddNeighbour(B, 5); O.AddNeighbour(C, 4); A.AddNeighbour(F, 12); A.AddNeighbour(D, 7); A.AddNeighbour(B, 2); B.AddNeighbour(D, 4); B.AddNeighbour(E, 3); B.AddNeighbour(C, 1); C.AddNeighbour(E, 4); D.AddNeighbour(T, 5); D.AddNeighbour(E, 1); E.AddNeighbour(T, 7); F.AddNeighbour(T, 3); var graph = new List<GraphNode<string>> { O, A, B, C, D, E, F, T }; var dijkstra = new Dijkstra<string>(graph); var path = dijkstra.FindShortestPathBetween(O, T); //The other alternate path //path[0].Value.ShouldBe("O"); //path[1].Value.ShouldBe("A"); //path[2].Value.ShouldBe("B"); //path[3].Value.ShouldBe("E"); //path[4].Value.ShouldBe("D"); //path[5].Value.ShouldBe("T"); path[0].Value.ShouldBe("O"); path[1].Value.ShouldBe("A"); path[2].Value.ShouldBe("B"); path[3].Value.ShouldBe("D"); path[4].Value.ShouldBe("T"); }
public void SetMap(Map map) { _source = map; _map = map.Dijkstra; }
private void InitializeAlgorithms() { _firstPageAlgorithm = _algorithm; ExamPage secondPage = ExamPages[1]; ObservableCollection<ComboboxElement> queue = new ObservableCollection<ComboboxElement>(); switch (this.AlgorithmName) { case "Przeszukiwanie wszerz": queue.Add( new ComboboxElement(0) ); _secondPageAlgorithm = new BFS(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue); break; case "Przeszukiwanie w głąb": _secondPageAlgorithm = new DFS(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes()); break; case "Sortowanie topologiczne": _secondPageAlgorithm = new TopologicalSort(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue); break; case "Algorytm Kruskala": _secondPageAlgorithm = new Kruskal(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes()); break; case "Wykrywanie dwudzielności": queue.Add(new ComboboxElement(0)); _secondPageAlgorithm = new Bipartition(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue); break; case "Algorytm Dijkstry": _secondPageAlgorithm = new Dijkstra(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes()); break; case "Algorytm Bellmana-Forda": queue.Add(new ComboboxElement(0)); _secondPageAlgorithm = new BellmanFord(secondPage.Graph.GetAllEdges(), secondPage.Graph.GetAllNodes(), queue); break; } }
static void Main(string[] args) { //var sw = new Stopwatch(); var tree = new Dictionary<string, Node>(); int n = int.Parse(Console.ReadLine()); // the number of adjacency relations for (int i = 0; i < n; i++) { string[] inputs = Console.ReadLine().Split(' '); var xi = inputs[0]; // the ID of a person which is adjacent to yi var yi = inputs[1]; // the ID of a person which is adjacent to xi var nodex = ensureNodeInTree(tree, xi); var nodey = ensureNodeInTree(tree, yi); nodex.Neighbours.Add(nodey); nodey.Neighbours.Add(nodex); } //Console.Error.WriteLine("{0}\tRead input with {1} links", sw.ElapsedMilliseconds, n); var persons = tree.Keys.ToArray(); var longestPath = 0; var firstPerson = ""; var tempStart = persons[0]; var bfs = new Dijkstra(tree, tempStart); //Console.Error.WriteLine("{0}\tCreated Dijkstra", sw.ElapsedMilliseconds); //Console.Error.WriteLine(string.Format("{0}\tScanning {1} persons", sw.ElapsedMilliseconds, persons.Length)); for (int i = 1; i < persons.Length; i++) { var l = bfs.Path(persons[i]); if (!l.HasValue) { Console.Error.WriteLine(string.Format("No path between {0} and {1}", bfs.From, persons[i])); } else if (l > longestPath) { longestPath = l.Value; firstPerson = persons[i]; } } //Console.Error.WriteLine("{0}\tFound first person: {1}. Path() used {2} ms.", sw.ElapsedMilliseconds, firstPerson, sw2.ElapsedMilliseconds); longestPath = 0; var secondPerson = ""; bfs.Reset(firstPerson); //Console.Error.WriteLine("{0}\tReset Dijkstra", sw.ElapsedMilliseconds); for (int i = 0; i < persons.Length; i++) { var l = bfs.Path(persons[i]); if (!l.HasValue) { Console.Error.WriteLine(string.Format("No path between {0} and {1}", bfs.From, persons[i])); } else if (l > longestPath) { longestPath = l.Value; secondPerson = persons[i]; } } //Console.Error.WriteLine("{0}\tFound second person: {1}", sw.ElapsedMilliseconds, secondPerson); Console.WriteLine((int)Math.Floor((longestPath + 1) / 2.0)); // The minimal amount of steps required to completely propagate the advertisement }
public List<PathFinderNode> FindPath(Point s,Point e) { s=Clamp(s); e=Clamp(e); int si=GetArrayIndex(s); int ei=GetArrayIndex(e); Console.WriteLine("FindPath: Initializing Dijkstra with {0}*{1}={2}",chan.Width,chan.Height,chan.Width*chan.Height); Dijkstra p = new Dijkstra( chan.Width*chan.Height, this.getInternodeTraversalCost, this.nearbyNodesHint); Console.WriteLine("FindPath: Locating path from {0} to {1}.",s,e); int[] PointPath=p.GetMinimumPath(si,ei); List<PathFinderNode> Path=new List<PathFinderNode>(); foreach(int pi in PointPath) { Point pt = GetPointFromArrayIndex(pi); PathFinderNode pfn=new PathFinderNode(); pfn.X=pt.X; pfn.Y=pt.Y; Path.Add(pfn); } return Path; }
private char selectNextDirection(Point[] players, int myPlayerIndex, bool debugMode) { // 2 // . // 0.....1 // . . // . . //start timer var me = players[myPlayerIndex]; var opponents = players.Except(new[] { me }).ToArray(); if (debugMode) Player.Debug("I'm at {0}", Point.From(me.Index, map.Width, map.Height)); MaxiMinState bestPath = null; var queue = new Queue<MaxiMinState>(); var nodes = nodesFrom(map); // push all my exits to queue bundled with opponents current positions queue.Enqueue(new MaxiMinState { Steps = new[] { me.Index }, Me = me.Index, Opponents = opponents.Select(x => x.Index).ToArray(), Score = 0 }); var counter = 0; // foreach position in queue while (queue.Any() && timer.ElapsedMilliseconds < MAX_AI_TIME_MS) { // position me at new position counter++; var state = queue.Dequeue(); var myPath = string.Join("-", state.Steps); // push all new exits to queue (with path) bundled with opponents new positions foreach (var exit in nodes[state.Me].Neighbours.ToArray())//.Where(x => x.Cost == 1.0) { if (timer.ElapsedMilliseconds >= MAX_AI_TIME_MS) { Console.Error.WriteLine("Looping through exits when time is up."); break; //Time is up } //if (debugMode) Console.Error.Write("{0}: Eval {1}->{2} [{3}]: ", counter, myPath, exit.Node.Id, string.Join(", ", state.Opponents)); if (state.Opponents.Any(x => x == exit.Node.Id)) { //if (debugMode) Console.Error.WriteLine("Walked into opponent"); continue; } // move opponents towards my new position var opponentNewPositions = new int[state.Opponents.Length]; for (int i = 0; i < state.Opponents.Length; i++) { if (timer.ElapsedMilliseconds >= MAX_AI_TIME_MS) { Console.Error.WriteLine("Looping through opponents when time is up."); break; //Time is up } var opponentPath = new Dijkstra(nodes, state.Opponents[i]); var newPosition = opponentPath.GetPathTo(exit.Node.Id).Skip(1).First(); if (newPosition == exit.Node.Id) { //if (debugMode) Console.Error.WriteLine("Killed by opponent"); break; } opponentNewPositions[i] = newPosition; } if (opponentNewPositions.Last() == 0) continue; //We were killed by opponent in inner loop or time is up var score = state.Score + valueOf(map[exit.Node.Id]); var newState = new MaxiMinState { Steps = state.Steps.Concat(new[] { exit.Node.Id }).ToArray(), Me = exit.Node.Id, Opponents = opponentNewPositions, Score = score }; if (bestPath == null || bestPath.Score < newState.Score) { bestPath = newState; if (debugMode) Console.Error.Write("{0}: Eval {1}->{2} [{3}]: ", counter, myPath, exit.Node.Id, string.Join(", ", state.Opponents)); if (debugMode) Console.Error.WriteLine("Score {0}", newState.Score); } //else //{ // if (debugMode) Console.Error.WriteLine("----- {0}", newState.Score); //} queue.Enqueue(newState); } // if queue empty or time is up, break } //walk towards the best path Player.Debug("Calculated {0} iterations. Best path is {1} steps.", counter, bestPath == null ? 0 : bestPath.Steps.Length); var nextTile = bestPath == null || bestPath.Steps.Length < 2 ? me.Index : bestPath.Steps.Skip(1).First(); //if (debugMode) Player.Debug("Moving to {0} through {1}", bestPath == null ? nextTile : bestPath.Me, nextTile); return map.DirectionTo(me, nextTile); }
public void ShouldKnowWhenNoPathEsists() { var one = new GraphNode<int>(1); var two = new GraphNode<int>(2); var three = new GraphNode<int>(3); var four = new GraphNode<int>(4); var five = new GraphNode<int>(5); var six = new GraphNode<int>(6); var seven = new GraphNode<int>(7); one.AddNeighbour(six, 14); one.AddNeighbour(three, 9); one.AddNeighbour(two, 7); two.AddNeighbour(three, 10); two.AddNeighbour(four, 15); three.AddNeighbour(six, 2); three.AddNeighbour(four, 11); four.AddNeighbour(five, 6); five.AddNeighbour(six, 9); var graph = new List<GraphNode<int>> { one, two, three, four, five, six, seven }; var dijkstra = new Dijkstra<int>(graph); var path = dijkstra.FindShortestPathBetween(one, seven); path.Count.ShouldBe(0); }