Example #1
0
        public void DijkstraTest3_Success()
        {
            var graph = new DirectedWeightedGraph <char>(5);
            var a     = graph.AddVertex('A');
            var b     = graph.AddVertex('B');
            var c     = graph.AddVertex('C');

            graph.AddEdge(a, b, 1);
            graph.AddEdge(b, a, 1);

            graph.AddEdge(a, c, 3);
            graph.AddEdge(c, a, 3);

            var shortestPathList = DijkstraAlgorithm.GenerateShortestPath(graph, a);

            shortestPathList.Length.Should().Be(3);
            shortestPathList[0].Vertex.Should().Be(a);
            shortestPathList[0].Distance.Should().Be(0);
            shortestPathList[0].PreviousVertex.Should().Be(a);
            shortestPathList[0].ToString().Should()
            .Be($"Vertex: {a} - Distance: {0} - Previous: {a}");

            shortestPathList[1].Vertex.Should().Be(b);
            shortestPathList[1].Distance.Should().Be(1);
            shortestPathList[1].PreviousVertex.Should().Be(a);
            shortestPathList[1].ToString().Should()
            .Be($"Vertex: {b} - Distance: {1} - Previous: {a}");

            shortestPathList[2].Vertex.Should().Be(c);
            shortestPathList[2].Distance.Should().Be(3);
            shortestPathList[2].PreviousVertex.Should().Be(a);
            shortestPathList[2].ToString().Should()
            .Be($"Vertex: {c} - Distance: {3} - Previous: {a}");
        }
Example #2
0
        private void RunBuntton_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_dGraph == null) //|| _dGraph.Vertices.Any(v => v.Visited))
            {
                MessageBox.Show("Загрузите новый лабиринт!", "Warning", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return;
            }
            //запускаем параллельно все наши алгоритмы
            if (dijkstraButton.Down)
            {
                Task.Run(() => DijkstraAlgorithm.Execute(_dGraph, dijkstraPanel, dijkstraFirst, dijkstraBest));
                return;
            }

            if (bfsButton.Down)
            {
                Task.Run(() => BreadthFirst.Execute(_bGraph, bFirstPanel, bfFirst, bfBest));
                return;
            }

            if (astarButton.Down)
            {
                Task.Run(() => AStar.Execute(_aGraph, aStarPanel, asFirst, asBest));
                return;
            }
            Task.Run(() => DijkstraAlgorithm.Execute(_dGraph, dijkstraPanel, dijkstraFirst, dijkstraBest));
            Task.Run(() => BreadthFirst.Execute(_bGraph, bFirstPanel, bfFirst, bfBest));
            Task.Run(() => AStar.Execute(_aGraph, aStarPanel, asFirst, asBest));
        }
            public void Test01()
            {
                const int numberOfVerteces = 9;
                var       graph            =
                    new GraphBuilder(numberOfVertices: numberOfVerteces, isDirected: false)
                    .AddEdge(0, 1, 10)
                    .AddEdge(0, 3, 4)
                    .AddEdge(0, 4, 17)
                    .AddEdge(1, 2, 3)
                    .AddEdge(1, 4, 7)
                    .AddEdge(3, 4, 15)
                    .AddEdge(3, 6, 2)
                    .AddEdge(4, 7, 3)
                    .AddEdge(6, 7, 3)
                    .AddEdge(2, 4, 5)
                    .AddEdge(2, 5, 6)
                    .AddEdge(5, 7, 1)
                    .AddEdge(2, 8, 7)
                    .AddEdge(7, 8, 19)
                    .AddEdge(5, 8, 27)
                    .ToGraph();
                const int startingVertex = 0;

                var result = DijkstraAlgorithm.ShortestPaths(new GraphWithTracking(graph), startingVertex);

                result.Count.Should().Be(numberOfVerteces);
                result.ShouldBeEquivalentTo(new[] { 0, 10, 13, 4, 12, 10, 6, 9, 20 });
            }
    /// <summary>
    /// Switch scene from 2D to navigation.
    /// </summary>
    public void MoveToNavigation()
    {
        if (nearestID == -1 || newSelectedID == -1)
        {
            AndroidHelper.ShowAndroidToastMessage("Please choose navigate marker!");
            return;
        }

        // create dijkstra function and computed shorted path for navigation
        DijkstraAlgorithm dijkstra = new DijkstraAlgorithm(graph2D, nearestID, newSelectedID);

        if (dijkstra.sPath == null)
        {
            AndroidHelper.ShowAndroidToastMessage("To this NavPoint does not have any path! Please repair graph.");
            return;
        }

        // before switching
        // disable all markers with renderers
        areaLearning.EnableDisableAllMarkers(false);
        // toggle scene settings from "create navigation map" to "navigate in 3D space"
        areaLearning.ToggleNavigationScene();
        // enable 3D camere with augmented reality rendering
        poseController.GetComponentInParent <Camera>().enabled = true;
        // show only markers for navigation
        areaLearning.ShowNavigationMarkers(dijkstra.sPath);

        foreach (GameObject canvas in GameObject.FindGameObjectsWithTag("Navigation2DMap"))
        {
            canvas.SetActive(false);
        }

        areaLearning.canvas2DTo3D.SetActive(true);
        SceneManager.UnloadSceneAsync("Navigation2DMap");
    }
Example #5
0
        public void DijkstraMethodTest()
        {
            // here test case is from https://youtu.be/pVfj6mxhdMw

            IGraph <char> graph = new Graph <char>();
            var           a     = graph.AddVertex('A');
            var           b     = graph.AddVertex('B');
            var           c     = graph.AddVertex('C');
            var           d     = graph.AddVertex('D');
            var           e     = graph.AddVertex('E');

            graph.AddEdge(a, b, 6);
            graph.AddEdge(b, a, 6);

            graph.AddEdge(a, d, 1);
            graph.AddEdge(d, a, 1);

            graph.AddEdge(d, e, 1);
            graph.AddEdge(e, d, 1);

            graph.AddEdge(d, b, 2);
            graph.AddEdge(b, d, 2);

            graph.AddEdge(e, b, 2);
            graph.AddEdge(b, e, 2);

            graph.AddEdge(e, c, 5);
            graph.AddEdge(c, e, 5);

            graph.AddEdge(c, b, 5);
            graph.AddEdge(b, c, 5);

            var shortestPathList = DijkstraAlgorithm <char> .DijkstraMethod(graph, a);

            shortestPathList.Count.Should().Be(5);

            shortestPathList[0].Vertex.Should().Be(a);
            shortestPathList[0].Distance.Should().Be(0);
            shortestPathList[0].PreviousVertex.Should().Be(a);

            shortestPathList[1].Vertex.Should().Be(b);
            shortestPathList[1].Distance.Should().Be(3);
            shortestPathList[1].PreviousVertex.Should().Be(d);

            shortestPathList[2].Vertex.Should().Be(d);
            shortestPathList[2].Distance.Should().Be(1);
            shortestPathList[2].PreviousVertex.Should().Be(a);

            shortestPathList[3].Vertex.Should().Be(e);
            shortestPathList[3].Distance.Should().Be(2);
            shortestPathList[3].PreviousVertex.Should().Be(d);

            shortestPathList[4].Vertex.Should().Be(c);
            shortestPathList[4].Distance.Should().Be(7);
            shortestPathList[4].PreviousVertex.Should().Be(e);

            graph.Reset();
            graph.IsTraversed.Should().BeFalse();
        }
 private static IEnumerable <string> FindShortestPathFor(ParseResult parseResult)
 {
     return(DijkstraAlgorithm.Run(
                parseResult.Start,
                parseResult.Finish,
                parseResult.AllButCrashedNodes
                )
            .Cast <Node>().Select(n => n.GetId()));
 }
Example #7
0
        public void Find_ValidInputUsingStringStructure_ShouldFindPath()
        {
            var graph = AdjacencyListFactory.CreateUndirectedFromStructure("1-[14]6-[9]3-[7]2,6-[9]5-[2]3,2-[10]3-[15]4,3-[11]4,4-[6]5");

            var search = new DijkstraAlgorithm(graph);
            var result = search.BuildPath("1").GetPathString("5");

            result.Should().Be("1365");
        }
Example #8
0
        /// <summary>
        /// Осуществляет поиск кратчайшего пути до необходимого типа постройки в «городе».
        /// Если построек такого типа несколько, то возвращает путь только до той, который оказался самым кратчайшим.
        /// Если не удалось найти, то возвращает пустой путь.
        /// </summary>
        /// <param name="graph">Граф, соответствующий городу, в котором будем искать путь.</param>
        /// <param name="startPoint">Стартовая точка, из которой ищем путь.</param>
        /// <param name="institutionType">Тип постройки, к которой ищем путь.</param>
        /// <returns>Объект с информацией о найденном или не найденном пути.</returns>
        public static PathInfo FindPathTo(Graph graph, Vertex startPoint, InstitutionType institutionType)
        {
            PathInfo shortestPath       = PathInfo.CreateEmptyPath();
            float    shortestPathLength = float.MaxValue;

            /**
             * Для нахождения вершин в графе, которые соответствуют нужной нам постройке,
             * осуществляется проход по всем вершинам, и ищется объект нужного нам типа.
             * Далее вызывается алгоритм Дейкстры до найденной вершины. Так повторяется до тех пор, пока
             * не пройдемся по всем нужным нам вершинам. Далее среди всех найденных путей ищется тот, который
             * является наикратчайшим.
             */

            foreach (Vertex vertex in graph.Vertices)
            {
                // Стартовая точка не может оказаться конечной.
                if (vertex == startPoint)
                {
                    continue;
                }

                Institution institution = vertex.Tag as Institution;
                if (institution != null && institution.GetInstitutionType() == institutionType)
                {
                    DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm(graph);
                    PathInfo          pathInfo          = dijkstraAlgorithm.FindShortestPath(startPoint, vertex);

                    if (pathInfo.IsEmptyPath())
                    {
                        continue;
                    }
                    if (pathInfo.TotalLength > shortestPathLength)
                    {
                        continue;
                    }

                    // На слишком малых расстояниях между узлами, может быть проблема, что дистанция одинаковая.
                    // Поэтому в таких случаях берем элемент с наименьшим числом узлов.
                    if (pathInfo.TotalLength == shortestPathLength)
                    {
                        if (pathInfo.Path.Length < shortestPath.Path.Length)
                        {
                            shortestPath       = pathInfo;
                            shortestPathLength = pathInfo.TotalLength;
                        }
                    }
                    else
                    {
                        shortestPath       = pathInfo;
                        shortestPathLength = pathInfo.TotalLength;
                    }
                }
            }

            return(shortestPath);
        }
Example #9
0
    private void Start()
    {
        _data   = GameObject.Find("Data").GetComponent <Data>();
        _height = _data.Height;
        _lenght = _data.Lenght;

        _step     = 1.28f;
        _djikstra = transform.GetComponent <DijkstraAlgorithm>();
        Spawn();
    }
 public HighTrainYesViewModel(string cityFilePath, string highTrainFilePath)
 {
     _cityFilePath      = cityFilePath;
     _highTrainFilePath = highTrainFilePath;
     Cities             = new ObservableCollection <CalculatorCity>();
     _dijkstra          = new DijkstraAlgorithm(NetWorkUtil.ReadRailway(_highTrainFilePath));
     _highTrainStation  = new Dictionary <string, RasterOp>(_dijkstra.Count);
     InitializeControls();
     InitializeCommand();
 }
        public static void Test_Genetic(string mesh_type)
        {
            int[] sizes_mesh = new int[21] {
                10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50
            };
            int[] final_positions = new int[21] {
                99, 143, 195, 255, 323, 399, 483, 575, 675, 783, 899, 1023, 1155, 1295, 1443, 1599, 1763, 1935, 2115, 2303, 2499
            };

            for (int i = 0; i < sizes_mesh.Length; i++)
            {
                string size      = "_" + sizes_mesh[i] + "x" + sizes_mesh[i] + ".txt";
                string file_name = mesh_type + size;

                Console.WriteLine("Init Execution -> " + file_name);

                //-------------------------------------------------------------------
                //Create the mesh environment
                MeshEnvironment env = new MeshEnvironment(_start: 0, _final: final_positions[i], _file_name: file_name, sizes_mesh[i]);
                env.InitEnviroment(type_mesh: mesh_type);

                //-------------------------------------------------------------------
                for (int j = 0; j < num_test; j++)
                {
                    env.FillDistanceMatrix();
                    DijkstraAlgorithm dk1 = new DijkstraAlgorithm();
                    dk1.Execute(ref env);

                    GeneticAlgorithm gn1 = new GeneticAlgorithm();
                    gn1.Execute(ref env);


                    //Insert the obstacle in a middle zone of the current optimal solution
                    InsertSeveralObstacle(ref env, num_obstacle: 2, num_routes: 2);

                    env.FillDistanceMatrix();
                    DijkstraAlgorithm dk2 = new DijkstraAlgorithm();
                    dk2.Execute(ref env);

                    GeneticAlgorithm gn2 = new GeneticAlgorithm();
                    gn2.Execute(ref env);

                    ////Store variables in a txt
                    Console.WriteLine("Execution {0} of " + file_name, j);

                    StoreVariable_Genetic(mesh_type, ref env, ref dk1, ref gn1, ref dk2, ref gn2);

                    env.ClearObstacles();
                }

                Console.WriteLine("End Execution -> " + file_name);
                Console.WriteLine("---------------------------------------------");
            }
        }
Example #12
0
        public void Test()
        {
            string chosenMap = "S 0 0 -5 D";
            var    map       = new Map(chosenMap);
            var    algorithm = new DijkstraAlgorithm(map.StartX, map.StartY, map.DestX, map.DestY, chosenMap);

            var result = algorithm.run();

            Assert.AreEqual(4, result.Probes.Count);
            Assert.AreEqual(5, result.Paths.Count);
        }
Example #13
0
        public void DijkstraMethodTest_ShouldThrow_VertexDoesntBelongToGraph()
        {
            var graph       = new DirectedWeightedGraph <char>(5);
            var startVertex = graph.AddVertex('A');

            Func <DistanceModel <char>[]> action = () => DijkstraAlgorithm.GenerateShortestPath(
                new DirectedWeightedGraph <char>(5), startVertex);

            action.Should().Throw <ArgumentNullException>()
            .WithMessage($"Value cannot be null. (Parameter '{nameof(graph)}')");
        }
Example #14
0
        public void Test1()
        {
            WaypointNode[] waypoints = new WaypointNode[13];
            for (int i = 0; i < 13; i++)
            {
                waypoints[i] = new WaypointNode();
            }
            waypoints[0].Weight = 0;
            waypoints[0].Ways.Add((1, waypoints[10]));
            waypoints[0].Ways.Add((1, waypoints[3]));
            waypoints[1].Ways.Add((1, waypoints[7]));
            waypoints[1].Ways.Add((1, waypoints[6]));
            waypoints[2].Ways.Add((1, waypoints[3]));
            waypoints[2].Ways.Add((1, waypoints[5]));
            waypoints[3].Ways.Add((1, waypoints[4]));
            waypoints[3].Ways.Add((1, waypoints[2]));
            waypoints[3].Ways.Add((1, waypoints[0]));
            waypoints[4].Ways.Add((1, waypoints[3]));
            waypoints[5].Ways.Add((1, waypoints[2]));
            waypoints[5].Ways.Add((1, waypoints[7]));
            waypoints[6].Ways.Add((1, waypoints[1]));
            waypoints[6].Ways.Add((1, waypoints[10]));
            waypoints[7].Ways.Add((1, waypoints[1]));
            waypoints[7].Ways.Add((1, waypoints[9]));
            waypoints[7].Ways.Add((1, waypoints[5]));
            waypoints[8].Ways.Add((1, waypoints[9]));
            waypoints[8].Ways.Add((1, waypoints[12]));
            waypoints[9].Ways.Add((1, waypoints[7]));
            waypoints[9].Ways.Add((1, waypoints[8]));
            waypoints[10].Ways.Add((1, waypoints[0]));
            waypoints[10].Ways.Add((1, waypoints[12]));
            waypoints[10].Ways.Add((1, waypoints[6]));
            waypoints[12].Ways.Add((1, waypoints[10]));
            waypoints[12].Ways.Add((1, waypoints[8]));

            var wp         = DijkstraAlgorithm.FindWay(waypoints[0], waypoints[7]);
            var res        = new List <int>();
            var realResult = new int[] { 0, 10, 6, 1, 7 };

            foreach (var element in wp)
            {
                for (int i = 0; i < 13; i++)
                {
                    if (waypoints[i] == element)
                    {
                        res.Add(i);
                    }
                }
            }
            for (int i = 0; i < realResult.Length; i++)
            {
                Assert.AreEqual(realResult[i], res[i]);
            }
        }
        public void ShoertPathWithoutPath()
        {
            var dijkstraAlgorithmt = new DijkstraAlgorithm();
            var path = dijkstraAlgorithmt.FindShortestPath(cityLS, cityNF, GetNeighboardhood(routes));


            Assert.Null(path.Distance);
            List <CityEntity> nodeVisitExpected = new List <CityEntity>();

            Assert.Equal(nodeVisitExpected, path.NodeVisit);
        }
Example #16
0
        public void Setup()
        {
            var factory  = new DefinitionNodeGridFactory();
            var nodeGrid = factory.GeneratePreFilledArray(GenerateNodeGridConnections.All, 320, 200);

            _definitionNodeGrid = new DefinitionNodeGrid(nodeGrid, new Vector2(1, 1));
            _dijkstraNodeGrid   = new DijkstraNodeGrid(_definitionNodeGrid, 1);
            _algorithm          = new DijkstraAlgorithm(_definitionNodeGrid.NodeCount);
            _pathRequest        = PathRequest.Create(Substitute.For <IPathfinder <NodePath> >(),
                                                     _definitionNodeGrid.NodeGrid.ToIndex(0, 0), _definitionNodeGrid.NodeGrid.ToIndex(319, 199));
            _nodeNetwork = _dijkstraNodeGrid.GetCollisionLayerNetwork(_pathRequest.CollisionCategory);
        }
        private NodePath RunDijkstra(DefinitionNodeGrid definitionNodeGrid, Point2 gridStart, Point2 gridEnd, out bool succes)
        {
            var dijkstraAlgorithm = new DijkstraAlgorithm(definitionNodeGrid.NodeCount);

            var start = definitionNodeGrid.NodeGrid.ToIndex(gridStart.X, gridStart.Y);
            var end   = definitionNodeGrid.NodeGrid.ToIndex(gridEnd.X, gridEnd.Y);

            var pathfindingNetwork = new DijkstraNodeGrid(definitionNodeGrid, 5);
            var pathRequest        = PathRequest.Create(Substitute.For <IPathfinder <IPath> >(), start, end, PathfindaxCollisionCategory.Cat1);

            return(dijkstraAlgorithm.FindPath(pathfindingNetwork, pathRequest, out succes));
        }
        public static void InsertSeveralObstacle(ref MeshEnvironment env, int num_obstacle, int num_routes)
        {
            for (int i = 0; i < num_routes; i++)
            {
                env.FillDistanceMatrix();
                DijkstraAlgorithm dk = new DijkstraAlgorithm();
                dk.Execute(ref env);

                //Ver bien como poner esto
                env.InsertObstacle(ref dk.final_best_path, num_obstacle);
            }
        }
Example #19
0
        public void ExecuteTest()
        {
            IGraph <string, string> graph = new AdjacencyMapGraph <string, string>();
            IVertex <string>        A     = graph.addVertex("A");
            IVertex <string>        B     = graph.addVertex("B");
            IVertex <string>        C     = graph.addVertex("C");
            IVertex <string>        D     = graph.addVertex("D");
            IVertex <string>        E     = graph.addVertex("E");
            IVertex <string>        F     = graph.addVertex("F");
            IVertex <string>        G     = graph.addVertex("G");
            IVertex <string>        H     = graph.addVertex("H");
            IVertex <string>        I     = graph.addVertex("I");
            IVertex <string>        J     = graph.addVertex("J");
            IVertex <string>        K     = graph.addVertex("K");
            IVertex <string>        L     = graph.addVertex("L");
            IVertex <string>        M     = graph.addVertex("M");
            IVertex <string>        N     = graph.addVertex("N");

            graph.addEdge(A, B, "1", 3);
            graph.addEdge(C, B, "2", 3);
            graph.addEdge(A, E, "3", 2);
            graph.addEdge(A, I, "4", 5);
            graph.addEdge(I, E, "5", 3);
            graph.addEdge(E, D, "6", 4);
            graph.addEdge(D, C, "7", 2);
            graph.addEdge(C, G, "8", 5);
            graph.addEdge(D, F, "9", 3);
            graph.addEdge(F, G, "10", 3);
            graph.addEdge(G, H, "11", 4);
            graph.addEdge(H, F, "12", 2);
            graph.addEdge(E, M, "13", 1);
            graph.addEdge(E, J, "14", 5);
            graph.addEdge(M, N, "15", 5);
            graph.addEdge(M, J, "16", 2);
            graph.addEdge(M, F, "17", 3);
            graph.addEdge(M, K, "18", 2);
            graph.addEdge(J, K, "19", 3);
            graph.addEdge(K, L, "20", 1);

            DijkstraAlgorithm <string, string> d = new DijkstraAlgorithm <string, string>(graph);

            d.Execute(A);

            StringBuilder sb = new StringBuilder();

            foreach (IVertex <string> v in d.getPredecessors().Keys)
            {
                sb.Append(v.ToString() + " from " + d.getPredecessors()[v].ToString() + Environment.NewLine);
            }

            MessageBox.Show(sb.ToString());
        }
        public void ShoertPathWStoBC()
        {
            var dijkstraAlgorithmt = new DijkstraAlgorithm();
            var path = dijkstraAlgorithmt.FindShortestPath(cityWS, cityBC, GetNeighboardhood(routes));


            Assert.Equal(5, path.Distance);
            List <CityEntity> nodeVisitExpected = new List <CityEntity> {
                cityWS, citySF, cityLV, cityBC
            };

            Assert.Equal(nodeVisitExpected, path.NodeVisit);
        }
Example #21
0
        public int FindShortestDistanceBetween(char start, char finish)
        {
            if (!NodeMap.ContainsKey(start) || !NodeMap.ContainsKey(finish))
            {
                return(-1);
            }

            var startNode  = NodeMap[start];
            var finishNode = NodeMap[finish];

            var results = DijkstraAlgorithm.Dijkstra(this, startNode, finishNode);

            return(results[finish]);
        }
Example #22
0
        private void buttonKruskal_Click(object sender, EventArgs e)
        {
            Stopwatch t = new Stopwatch();

            t.Start();
            var p = KruskalAlgorithm.Kruskal(graph);

            t.Stop();

            Graph dist = new Graph();

            foreach (var x in graph.Nodes)
            {
                dist.AddNode(x);
            }

            double cost = 0;

            for (int i = 0; i < p.Length / 2; i++)
            {
                foreach (var x in graph.Edges)
                {
                    if (x.From.Id == p[i, 0] && x.To.Id == p[i, 1] || x.From.Id == p[i, 1] && x.To.Id == p[i, 0])
                    {
                        x.IsMinE = true;
                        cost    += x.Weight;
                        dist.AddEdge(x);
                    }
                }
            }


            cost = 0;
            var distRez = DijkstraAlgorithm.Dijkstra(GraphRepresentation.toWeightMatrix(dist), 0, dist.Nodes.Count);

            textBoxResult.Text = "Расстояние в метрах от главного коммутатора до: \n\r";

            for (int i = 1; i < dist.Nodes.Count; i++)
            {
                textBoxResult.Text += "Коммутатора " + i + " = " + distRez[i] + " м." + Environment.NewLine;
                cost += distRez[i];
            }


            labelCost.Text = "Итоговая стоимость (р) " + cost * Convert.ToDouble(textBoxCost.Text);
            labelTime.Text = "Время в тиках " + t.ElapsedTicks;

            Repaint();
        }
Example #23
0
        public void DijkstraTest4_Success()
        {
            var graph = new DirectedWeightedGraph <char>(5);
            var a     = graph.AddVertex('A');
            var b     = graph.AddVertex('B');
            var c     = graph.AddVertex('C');
            var d     = graph.AddVertex('D');

            graph.AddEdge(a, b, 1);
            graph.AddEdge(b, a, 1);

            graph.AddEdge(a, c, 3);
            graph.AddEdge(c, a, 3);

            graph.AddEdge(c, d, 5);
            graph.AddEdge(d, c, 5);

            var shortestPathList = DijkstraAlgorithm.GenerateShortestPath(graph, a);

            shortestPathList.Length.Should().Be(4);
            shortestPathList[0].Vertex.Should().Be(a);
            shortestPathList[0].Distance.Should().Be(0);
            shortestPathList[0].PreviousVertex.Should().Be(a);
            shortestPathList[0].ToString().Should()
            .Be($"Vertex: {a} - Distance: {0} - Previous: {a}");

            shortestPathList[1].Vertex.Should().Be(b);
            shortestPathList[1].Distance.Should().Be(1);
            shortestPathList[1].PreviousVertex.Should().Be(a);
            shortestPathList[1].ToString().Should()
            .Be($"Vertex: {b} - Distance: {1} - Previous: {a}");

            shortestPathList[2].Vertex.Should().Be(c);
            shortestPathList[2].Distance.Should().Be(3);
            shortestPathList[2].PreviousVertex.Should().Be(a);
            shortestPathList[2].ToString().Should()
            .Be($"Vertex: {c} - Distance: {3} - Previous: {a}");

            // Vertex D won't be visited in this dijkstra implementation which is valid only for cyclic graphs,
            // since it is necessary to backtrack all unvisited vertices and place them
            // to the priority queue, which is not implemented yet in this repository.
            // If algo goes to the next vertex with minimal distance and this vertex is leaf -- algorithm stops.
            shortestPathList[3].Vertex.Should().Be(d);
            shortestPathList[3].Distance.Should().Be(double.MaxValue);
            shortestPathList[3].PreviousVertex.Should().BeNull();
            shortestPathList[3].ToString().Should()
            .Be($"Vertex: {d} - Distance: {double.MaxValue} - Previous: {null}");
        }
Example #24
0
        public void Test2()
        {
            WaypointNode[] waypoints = new WaypointNode[8];
            for (int i = 0; i < 8; i++)
            {
                waypoints[i] = new WaypointNode();
            }
            waypoints[1].Weight = 0;
            waypoints[1].Ways.Add((2, waypoints[2]));
            waypoints[2].Ways.Add((5, waypoints[3]));
            waypoints[2].Ways.Add((2, waypoints[1]));
            waypoints[2].Ways.Add((13, waypoints[5]));
            waypoints[3].Ways.Add((5, waypoints[2]));
            waypoints[3].Ways.Add((1, waypoints[4]));
            waypoints[4].Ways.Add((1, waypoints[3]));
            waypoints[4].Ways.Add((7, waypoints[5]));
            waypoints[4].Ways.Add((6, waypoints[6]));
            waypoints[5].Ways.Add((13, waypoints[2]));
            waypoints[5].Ways.Add((5, waypoints[7]));
            waypoints[5].Ways.Add((7, waypoints[4]));
            waypoints[6].Ways.Add((6, waypoints[4]));
            waypoints[6].Ways.Add((4, waypoints[7]));
            waypoints[7].Ways.Add((5, waypoints[5]));
            waypoints[7].Ways.Add((10, waypoints[0]));
            waypoints[7].Ways.Add((4, waypoints[6]));
            waypoints[0].Ways.Add((10, waypoints[7]));

            var wp         = DijkstraAlgorithm.FindWay(waypoints[1], waypoints[0]);
            var res        = new List <int>();
            var realResult = new int[] { 1, 2, 3, 4, 6, 7, 0 };

            foreach (var element in wp)
            {
                for (int i = 0; i < 8; i++)
                {
                    if (waypoints[i] == element)
                    {
                        res.Add(i);
                    }
                }
            }
            Assert.AreEqual(realResult.Length, res.Count);
            for (int i = 0; i < realResult.Length; i++)
            {
                Assert.AreEqual(realResult[i], res[i]);
            }
        }
Example #25
0
        public void TestDijkstra()
        {
            var vertices = new int[] { 1, 2, 3, 4, 5, 6 };
            var edges = new int[,]
            {
                { -1, 7, 9, -1, -1, 14 },
                { 7, -1, 10, 15, -1, -1 },
                { 8, 10, -1, 11, -1, 2 },
                { -1, 15, 11, -1, 6, -1 },
                { -1, -1, -1, 6, -1, 9 },
                { 14, -1, 2, -1, 9, -1}
            };

            var dijkstra = new DijkstraAlgorithm<int>(vertices, edges);
            var path = dijkstra.FindPath(0, 4);
            CollectionAssert.AreEqual(path, new int[] { 1, 3, 6, 5 });
        }
            public void Test03()
            {
                const int numberOfVerteces = 4;
                var       graph            =
                    new GraphBuilder(numberOfVertices: numberOfVerteces, isDirected: false)
                    .AddEdge(0, 1, 1)
                    .AddEdge(0, 2, 2)
                    .AddEdge(0, 3, 17)
                    .AddEdge(1, 2, 5)
                    .AddEdge(2, 3, 4)
                    .ToGraph();
                const int startingVertex = 2;

                var result = DijkstraAlgorithm.ShortestPaths(new GraphWithTracking(graph), startingVertex);

                result.Count.Should().Be(numberOfVerteces);
                result.ShouldBeEquivalentTo(new[] { 2, 3, 0, 4 });
            }
        public void TestFindShortestPath1()
        {
            Graph             graph             = DataGenerator.GenerateTestCityGraph();
            DijkstraAlgorithm dijkstraAlgorithm = new DijkstraAlgorithm(graph);

            Vertex   startVertex = graph.Vertices[0]; // 10;0
            Vertex   endVertex   = graph.Vertices[8]; // 0;0
            PathInfo pathInfo    = dijkstraAlgorithm.FindShortestPath(startVertex, endVertex);

            Assert.AreEqual(5, pathInfo.Path.Length);
            Assert.AreEqual(10, pathInfo.TotalLength);

            startVertex = graph.Vertices[1]; // 10;10
            endVertex   = graph.Vertices[2]; // 10;11
            pathInfo    = dijkstraAlgorithm.FindShortestPath(startVertex, endVertex);
            Assert.AreEqual(2, pathInfo.Path.Length);
            Assert.AreEqual(1, pathInfo.TotalLength);
        }
Example #28
0
        public void TestDijkstra()
        {
            var vertices = new int[] { 1, 2, 3, 4, 5, 6 };
            var edges    = new int[, ]
            {
                { -1, 7, 9, -1, -1, 14 },
                { 7, -1, 10, 15, -1, -1 },
                { 8, 10, -1, 11, -1, 2 },
                { -1, 15, 11, -1, 6, -1 },
                { -1, -1, -1, 6, -1, 9 },
                { 14, -1, 2, -1, 9, -1 }
            };

            var dijkstra = new DijkstraAlgorithm <int>(vertices, edges);
            var path     = dijkstra.FindPath(0, 4);

            CollectionAssert.AreEqual(path, new int[] { 1, 3, 6, 5 });
        }
Example #29
0
        private void NewToolStripMenuItemClick(object sender, EventArgs e)
        {
            graph = new Graph(Convert.ToInt32(numericVertexCount.Value), Convert.ToInt32(numericConnectionsCount.Value));
            if (graphicsOutputOn.Checked)
            {
                painter        = new Painter();
                picture1.Image = painter.GetImageFromGraph(graph);

                if (ApfCheckBox.Checked)
                {
                    var dijkstra = new DijkstraAlgorithm(graph);
                    painter.DrawPath(graph, dijkstra.GetPath());
                }
            }
            else
            {
                picture1.Image = null;
            }
        }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape) && oldPath != null)
        {
            if (oldPath != null)
            {
                coloredPath(oldPath, Color.white);
            }
            startPosition    = null;
            endPosition      = null;
            oldStartPosition = null;
            oldEndPosition   = null;
            oldPath          = null;
        }

        if (startPosition != null && startPosition != oldStartPosition)
        {
            makeGraph();
            findPathes       = DijkstraAlgorithm.FindPathes(startPosition, otherGraph);
            oldStartPosition = startPosition;
        }

        if (endPosition != null && endPosition != oldEndPosition && startPosition != endPosition)
        {
            var path = findPathes.Find(e => e.Count > 0 && Equals(e[e.Count - 1], endPosition));
            if (path != null)
            {
                if (oldPath != null)
                {
                    coloredPath(oldPath, Color.white);
                    for (int j = 0; j < oldEndPosition.transform.childCount; j++)
                    {
                        oldEndPosition.transform.GetChild(j).GetComponent <SpriteRenderer>().color = Color.white;
                    }
                }

                fillOldPath(path);
                coloredPath(path, new Color(0, 255, 0, 0.5f));
                oldEndPosition = endPosition;
            }
        }
    }
Example #31
0
        public void Find_ValidInput_ShouldFindPath()
        {
            var graph = AdjacencyListFactory.CreateUndirected();

            graph.AddVertex("a")
            .AddEdge("b", 5)
            .AddEdge("d", 10)
            .AddEdge("e", 19);
            graph.AddVertex("b")
            .AddEdge("c", 1)
            .AddEdge("d", 8);
            graph.AddVertex("d")
            .AddEdge("c", 1)
            .AddEdge("e", 9);

            var search = new DijkstraAlgorithm(graph);
            var result = search.BuildPath("a").GetPathString("e");

            result.Should().Be("abcde");
        }