Ejemplo n.º 1
0
    /// <summary>
    /// Check if there is at least one path for the random block Node.
    /// </summary>
    private bool CheckRouteForBlockNode(Node node, List <Transform> blockPath)
    {
        bool result = false;

        node.setWalkable(false);
        blockPath.Add(node.transform);

        ShortestPath finder = gameObject.GetComponent <ShortestPath>();

        if (finder == null)
        {
            finder = new ShortestPath();
        }

        GameObject startNode = GameObject.Find("node (" + this.Xstart + "," + this.Ystart + ")");
        GameObject endNode   = GameObject.Find("node (" + this.Xend + "," + this.Yend + ")");

        List <Transform> paths = finder.findShortestPath(startNode.transform, endNode.transform, "Dijkstra");

        if (paths.Count <= 1)
        {
            result = false;
        }
        else
        {
            result = true;
        }


        node.setWalkable(true);
        blockPath.Remove(node.transform);
        return(result);
    }
Ejemplo n.º 2
0
    public void TestCase_4()
    {
        // Expected answer: -2
        // Arrange
        FileReader fileReader = new FileReader();
        Dictionary <int, List <(int?, int)> > adjGraph = fileReader.ReadFile(@"C:\Users\Paul\Documents\Open Source Society for Computer Science (OSSU)\Algorithms Coursera\Programming Assignments\Week 13 Programming Assignment\TestCases\TestCase4.txt");
        ShortestPath shortestPath = new ShortestPath();

        // Act
        string shortestCost = "";

        foreach (KeyValuePair <int, List <(int?, int)> > entry in adjGraph)
        {
            int s = entry.Key - 1;
            Console.WriteLine("-source vertex: " + entry.Key + "----------");
            string bellman = shortestPath.Bellman_Ford(adjGraph, s);

            if (bellman == Globals.NegativeCycle())
            {
                shortestCost = bellman;
            }
        }

        // Assert
        Assert.Equal(Globals.NegativeCycle(), shortestCost);
    }
Ejemplo n.º 3
0
    static void Main()
    {
        var(h, w) = Read2();
        var s = GraphConsole.ReadEnclosedGrid(ref h, ref w);

        var sv = (h - 2, w - 1);
        var ev = (1, 1);

        var r = ShortestPath.ForGrid(h, w)
                .ForWeightedMap(v =>
        {
            var nes = new List <Edge <Point> >();
            var uv  = v - new Point(1, 0);
            var lv  = v - new Point(0, 1);
            if (s.GetValue(uv) != '#')
            {
                nes.Add(new Edge <Point>(v, uv, s.GetValue(uv) == 'S' ? 0 : 1));
            }
            if (s.GetValue(lv) != '#')
            {
                nes.Add(new Edge <Point>(v, lv, s.GetValue(lv) == 'E' ? 0 : 1));
            }
            return(nes.ToArray());
        })
                .BfsMod(2, sv, ev);

        Console.WriteLine(r[ev]);
    }
Ejemplo n.º 4
0
        public ShortestPath GetPathToTarget(GameLocation sourceLocation, GameLocation targetLocation)
        {
            var partialGraphs = this.FindPartialGraph(sourceLocation);
            var playerVertex  = partialGraphs.PlayerVertex;

            this.dijkstra.Compute(playerVertex);
            var b = this.distObserver;
            var c = this.predecessorObserver;

            var targetVertex = this.FindPartialGraph(targetLocation).TargetVertex;
            var path         = (IEnumerable <StardewEdge>) new List <StardewEdge>();
            var success      = this.predecessorObserver.TryGetPath(targetVertex, out path);
            var pathSimple   = new ShortestPath();

            if (success)
            {
                foreach (var pathPart in path)
                {
                    if (pathPart.Source != playerVertex)
                    {
                        pathSimple.AddStep(pathPart.Source.Location, pathPart.Source.Position);
                    }
                }

                return(pathSimple);
            }
            else
            {
                return(null);
            }
        }
        public void UseRoads()
        {
            //https://www.redblobgames.com/pathfinding/a-star/introduction.html
            var shortest = new ShortestPath();
            var map      = new TerrainMap(shortest);

            map.InitializeBoard(6, 6);

            map[1, 2].Roads = RoadType.Road2 | RoadType.Road5;
            map[2, 3].Roads = RoadType.Road2 | RoadType.Road5;
            map[3, 3].Roads = RoadType.Road3 | RoadType.Road5;
            map[4, 3].Roads = RoadType.Road2 | RoadType.Road6;
            map[5, 3].Roads = RoadType.Road5 | RoadType.Road1;
            map[5, 4].Roads = RoadType.Road1 | RoadType.Road4;
            map[5, 5].Roads = RoadType.Road4;

            shortest.ComputeShortestPath(map, 1, 2, 5, 5, 0);

            Assert.Equal(new Offset(2, 3), shortest.WayPoint[0]);
            Assert.Equal(new Offset(3, 3), shortest.WayPoint[1]);
            Assert.Equal(new Offset(4, 3), shortest.WayPoint[2]);
            Assert.Equal(new Offset(5, 3), shortest.WayPoint[3]);
            Assert.Equal(new Offset(5, 4), shortest.WayPoint[4]);
            Assert.Equal(new Offset(5, 5), shortest.WayPoint[5]);
        }
        public void FindShortestPath()
        {
            var shortest = new ShortestPath();
            var map      = new TerrainMap(shortest);

            map.InitializeBoard(10, 10);

            //mountains 4,1 - 4,8
            for (var i = 1; i < 9; i++)
            {
                var cube = HexGridMath.OffsetToCube(4, i);
                map[4, i] = new TerrainCell(cube.X, cube.Y, cube.Z, 30);
            }

            // 1,3 to 8,4
            shortest.ComputeShortestPath(map, 1, 3, 8, 4, 0);

            Assert.Equal(new Offset(2, 3), shortest.WayPoint[0]);
            Assert.Equal(new Offset(3, 2), shortest.WayPoint[1]);
            Assert.Equal(new Offset(3, 1), shortest.WayPoint[2]);
            Assert.Equal(new Offset(3, 0), shortest.WayPoint[3]);
            Assert.Equal(new Offset(4, 0), shortest.WayPoint[4]);
            Assert.Equal(new Offset(5, 0), shortest.WayPoint[5]);
            Assert.Equal(new Offset(6, 1), shortest.WayPoint[6]);
            Assert.Equal(new Offset(7, 1), shortest.WayPoint[7]);
            Assert.Equal(new Offset(8, 2), shortest.WayPoint[8]);
            Assert.Equal(new Offset(8, 3), shortest.WayPoint[9]);
            Assert.Equal(new Offset(8, 4), shortest.WayPoint[10]);
        }
Ejemplo n.º 7
0
    static void Main()
    {
        var(h, w) = Read2();
        var z  = Read();
        var sv = (z[0], z[1]);
        var ev = (z[2], z[3]);
        var s  = GraphConsole.ReadEnclosedGrid(ref h, ref w);

        var r1 = ShortestPath.ForGrid(h, w)
                 .ForUnweightedMap(v =>
        {
            var nvs = (v.i + v.j) % 2 == 0 ? Nexts1(v) : Nexts2(v);
            return(Array.FindAll(nvs, nv => s.GetValue(nv) != '#'));
        })
                 .Bfs(sv, ev);
        var r2 = ShortestPath.ForGrid(h, w)
                 .ForUnweightedMap(v =>
        {
            var nvs = (v.i + v.j) % 2 != 0 ? Nexts1(v) : Nexts2(v);
            return(Array.FindAll(nvs, nv => s.GetValue(nv) != '#'));
        })
                 .Bfs(sv, ev);

        var m = Math.Min(r1[ev], r2[ev]);

        Console.WriteLine(m == long.MaxValue ? -1 : m);

        Point[] Nexts1(Point v) => new[] { new Point(v.i - 1, v.j), new Point(v.i + 1, v.j) };
        Point[] Nexts2(Point v) => new[] { new Point(v.i, v.j - 1), new Point(v.i, v.j + 1) };
    }
Ejemplo n.º 8
0
        public void CalculateZeroCitiesLength()
        {
            ShortestPath path = new ShortestPath();

            double length = path.CalculatePerimeter(new List <Point>());

            Assert.That(length, Is.EqualTo(0));
        }
Ejemplo n.º 9
0
        private void ModifyArcWeightAtPosition(ShortestPath p, int i)
        {
            Node       origin      = p.OrderedNodes[i];
            Node       destination = p.OrderedNodes[i + 1];
            DynamicArc arc         = (DynamicArc)(p.OrderedArcs.Find(a => a.Origin.Equals(origin) && a.Destination.Equals(destination)));

            DenyArc(arc);
        }
Ejemplo n.º 10
0
        public void FindPath_StartPosition_IsTheSameAsProvidedStartPosition()
        {
            var startPosition = new Position(3, 3, 0);
            var sut = new ShortestPath(_mockMap.Object);
            var results = sut.FindPath(startPosition, 1);

            Assert.That(results.Select(x => x.StartPosition).Distinct().Single(), Is.EqualTo(startPosition));
        }
        private void add_distination_Click(object sender, RoutedEventArgs e)
        {
            distination_number = Int32.Parse(Node_distination.Text);
            dijkstra           = new ShortestPath(graph_matrix, VerticsNum, distination_number - 1);
            dijkstraForm       = new dijkstraViewer(dijkstra);

            printDijkstraGraph(graph_matrix, VerticsNum, dijkstra.distance);
        }
Ejemplo n.º 12
0
        public void ComputeDistance(string graphText, int expectedDistance)
        {
            var graph = graphText.ToGraph<string, int>();

            var algo = new ShortestPath<string>(graph);
            var distance = algo.ComputeDistance(graph["start"], graph["end"]);

            Assert.That(distance, Is.EqualTo(expectedDistance), "Shortest path not found.");
        }
Ejemplo n.º 13
0
 public dijkstraViewer(ShortestPath shortest)
 {
     InitializeComponent();
     this.dijkstra     = new ShortestPath(shortest.graphMatrix, shortest.numberOfVertics, shortest.secondNode);
     findNextNode      = true;
     calculateDistance = false;
     finish            = false;
     node = 0;
 }
Ejemplo n.º 14
0
 public EnemyPacket(Enemy enemy, int amount, float startTime, float spawnRate, ShortestPath _shortestPath)
 {
     this.enemy         = enemy;
     this.Amount        = amount;
     this.StartTime     = startTime;
     this.SpawnRate     = spawnRate;
     this._shortestPath = _shortestPath;
     _canSpawn          = false;
 }
    public DijkstraAllPairSP(EdgeWeightedDigraph g)
    {
        all = new ShortestPath[g.Vertice];

        for (int i = 0; i < g.Vertice; i++)
        {
            all[i] = new ShortestPath(g, i);
        }
    }
Ejemplo n.º 16
0
    static void Main(string[] args)
    {
        int n, m, s, t;

        sc.Multi(out n, out m);
        sc.Multi(out s, out t);
        --s;
        --t;
        var edge = new List <pair <long, int> > [n];

        for (int i = 0; i < n; i++)
        {
            edge[i] = new List <pair <long, int> >();
        }
        for (int i = 0; i < m; i++)
        {
            int  a, b;
            long d;
            sc.Multi(out a, out b, out d);
            --a;
            --b;
            edge[a].Add(make_pair(d, b));
            edge[b].Add(make_pair(d, a));
        }
        var sp = new ShortestPath <long>(LM);

        long[] cs, ct;
        var    ds  = sp.Dijkstra(edge, s, out cs, M);
        var    dt  = sp.Dijkstra(edge, t, out ct, M);
        long   l   = ds[t];
        long   ans = cs[t] * cs[t] % M;

        if (l % 2 == 0)
        {
            for (int i = 0; i < n; i++)
            {
                if (ds[i] == l / 2 && dt[i] == l / 2)
                {
                    ans = ((ans - cs[i] * cs[i] % M * ct[i] % M * ct[i]) % M + M) % M;
                }
            }
        }
        for (int i = 0; i < n; i++)
        {
            foreach (var item in edge[i])
            {
                int j = item.v2;
                if (ds[i] + dt[i] == l && ds[j] + dt[j] == l && ds[i] + item.v1 == ds[j] && ds[i] * 2 < l && ds[j] * 2 > l)
                {
                    ans = ((ans - cs[i] * cs[i] % M * ct[j] % M * ct[j]) % M + M) % M;
                }
            }
        }
        Prt(ans);
        sw.Flush();
    }
Ejemplo n.º 17
0
        public void GetLengthByCordsFromRootTest()
        {
            ShortestPath path  = new ShortestPath();
            Point        root  = new Point(0, 0);
            Point        point = new Point(3, 4);

            var length = path.CalculateLength(root, point);

            Assert.That(length, Is.EqualTo(5));
        }
Ejemplo n.º 18
0
        public void GetLengthByCordsTest()
        {
            ShortestPath path  = new ShortestPath();
            Point        root  = new Point(2, 3);
            Point        point = new Point(3, 4);

            var length = path.CalculateLength(root, point);

            Assert.That(length, Is.EqualTo(Math.Sqrt(2)));
        }
        public void ShortestPathTest1()
        {
            var path = ShortestPath.ShorthestPath(m_graph, vertices[0], vertices[4]).ToList();
            var exp  = new List <Vertex>()
            {
                vertices[0], vertices[2], vertices[3], vertices[4]
            };

            Assert.AreEqual(exp, path);
        }
Ejemplo n.º 20
0
 static void Main(string[] args)
 {
     int i = ShortestPath.GetKightShortestPath(new Node()
     {
         x = 0, y = 0
     }, new Node()
     {
         x = 7, y = 5
     });
 }
Ejemplo n.º 21
0
 // Start is called before the first frame update
 void Start()
 {
     timeForSpawn           = 0.1f;
     spawnDelay             = 1f;
     shortestPathAlgorithm  = GameObject.Find("Manager").GetComponent <ShortestPath>();
     mapManagerScript       = GameObject.Find("Manager").GetComponent <MapManager>();
     collisionManagerScript = GameObject.Find("Manager").GetComponent <CollisionManager>();
     FindPathToDestination();
     currentIndex = 0;
     Invoke("UpdatePosition", Constants.UpdateMethodDelay);
 }
Ejemplo n.º 22
0
        public void CalculateSingleCitiesLength()
        {
            ShortestPath path   = new ShortestPath();
            Point        root   = new Point(2, 3);
            double       length = path.CalculatePerimeter(new List <Point>()
            {
                root
            });

            Assert.That(length, Is.EqualTo(0));
        }
Ejemplo n.º 23
0
 private void UpdateResultPath(ShortestPath path)
 {
     foreach (var node in path.OrderedNodes)
     {
         var cell = Cells.First(c => c.Id == node.Id);
         if (cell.CellState != CellState.IsSelected)
         {
             cell.CellState = CellState.IsPath;
         }
     }
 }
Ejemplo n.º 24
0
        public void FindPath_WhenDistanceIsThreeFromPos3x3_ReturnsAdjacentSpacesByShortestPath(int x, int y, decimal expectedMaxDistance)
        {
            var positionToCheck = new Position(x, y, 0);

            var startPosition = new Position(3, 3, 0);
            var sut = new ShortestPath(_mockMap.Object);
            var results = sut.FindPath(startPosition, 3);

            var path = results.Single(p => p.EndPosition == positionToCheck);
            path.PathPositions.ToList().ForEach(p => Debug.WriteLine(p));
            Assert.That(path.Distance, Is.InRange(expectedMaxDistance - 0.25M, expectedMaxDistance));
        }
Ejemplo n.º 25
0
        public void ShortestPathTest()
        {
            string fileName = @"Graph\testG2.txt";
            var    g1       = new SparseGraph <double>(7, false);
            var    gr1      = new ReadGraph <double>(g1, fileName);

            g1.Show();
            var path = new ShortestPath <double>(g1, 0);

            Console.WriteLine("BFS: ");
            path.ShowPath(6);
        }
Ejemplo n.º 26
0
        public void CalculateTwoCitiesLength()
        {
            ShortestPath path   = new ShortestPath();
            Point        city1  = new Point(0, 0);
            Point        city2  = new Point(3, 4);
            double       length = path.CalculatePerimeter(new List <Point>()
            {
                city1, city2
            });

            Assert.That(length, Is.EqualTo(5));
        }
Ejemplo n.º 27
0
 private void CancelRootNodes(ShortestPath path, int i)
 {
     //set all outgoing connections for the nodes in the root of
     //the path to infinity so that these nodes wont be part of a shortest path anymore
     for (int j = 0; j < i; j++)
     {
         foreach (DynamicArc incidentArc in path.OrderedNodes[j].OutgoingConnections)
         {
             DenyArc(incidentArc);
         }
     }
 }
        public void ShortestDistanceTestDirected()
        {
            var dis = ShortestPath.ShorthestDistance(m_graphDirected, vertices[0], vertices[4]);
            var exp = Vector2.Distance(vertices[0].Pos, vertices[2].Pos) +
                      Vector2.Distance(vertices[2].Pos, vertices[3].Pos) +
                      Vector2.Distance(vertices[3].Pos, vertices[4].Pos);

            Assert.AreEqual(exp, dis, MathUtil.EPS);

            var dis2 = ShortestPath.ShorthestDistance(m_graphDirected, vertices[4], vertices[0]);

            Assert.AreEqual(float.PositiveInfinity, dis2);
        }
Ejemplo n.º 29
0
        public void UpdatePath()
        {
            var targetLocation = this.ObjectInfoList.FirstOrDefault(x => x.NeedAction)?.Location;

            if (targetLocation != null)
            {
                this.path = Graph.GetPathToTarget(Game1.currentLocation, targetLocation);
            }
            else
            {
                this.path = null;
            }
        }
Ejemplo n.º 30
0
        public void CalculateThreeCitiesLength()
        {
            ShortestPath path   = new ShortestPath();
            Point        city1  = new Point(0, 0);
            Point        city2  = new Point(2, 3);
            Point        city3  = new Point(3, 4);
            double       length = path.CalculatePerimeter(new List <Point>()
            {
                city1, city2, city3
            });

            Assert.That(length, Is.EqualTo(Math.Sqrt(13) + Math.Sqrt(2) + 5));
        }
Ejemplo n.º 31
0
        public async Task <string> Run(string startWord, string endWord)
        {
            var result = await _wordProcessor.Run(startWord, endWord);

            var path         = new ShortestPath();
            var shortestPath = path.GetShortestPath(new List <Word>()
            {
                result
            }, endWord);
            var formattedResult = FormatResult(shortestPath);
            await _fileService.SaveToFile(_config.Value.ResultPath, formattedResult);

            return(formattedResult);
        }
        public void ShortestDistanceTest2()
        {
            var dis = ShortestPath.ShorthestDistance(m_graph, vertices[3], vertices[5]);
            var exp = Vector2.Distance(vertices[3].Pos, vertices[2].Pos) +
                      Vector2.Distance(vertices[2].Pos, vertices[0].Pos) +
                      Vector2.Distance(vertices[0].Pos, vertices[5].Pos);

            Assert.AreEqual(exp, dis, MathUtil.EPS);

            // check if opposite direction is equal (undirected graph)
            var dis2 = ShortestPath.ShorthestDistance(m_graph, vertices[5], vertices[3]);

            Assert.AreEqual(dis, dis2, MathUtil.EPS);
        }
Ejemplo n.º 33
0
        public void ShortestPathShouldWork()
        {
            var input = new char[][]
            {
                new char[] { 'w', 'x' },
                new char[] { 'x', 'y' },
                new char[] { 'z', 'y' },
                new char[] { 'z', 'v' },
                new char[] { 'w', 'v' },
            };

            var result = ShortestPath.GetShortestPath(input, 'w', 'z');

            Assert.Equal(2, result);
        }
Ejemplo n.º 34
0
        public void FindPath_WhenDistanceIsOne_OnlyReturnsAdjacentSpaces()
        {
            var expectedResults = new[]{
                                          new Position(3,4,0),
                                          new Position(2,3,0),
                                          new Position(3,2,0),
                                          new Position(4,3,0),
                                       };

            var startPosition = new Position(3, 3, 0);
            var sut = new ShortestPath(_mockMap.Object);
            var results = sut.FindPath(startPosition, 1);

            Assert.That(Sort(results.Select(x => x.EndPosition)), Is.EquivalentTo(Sort(expectedResults)));
        }
Ejemplo n.º 35
0
        public Path FindPath(MapNode start, List<MapNode> targets, int limit)
        {
            Path path = null;

            List<MapNode> list = new ShortestPath(mapManager, beamTarget).FindPath(start, targets);
            if (list == null || list.Count == 0)
                return null;

            foreach (MapNode node in list)
            {
                TheLogger.Debug(node.ToString() + "\n");
            }

            list.Reverse();
            path = new Path();
            path.mapnodes = new Stack<MapNode>(list);
            return path;
        }
Ejemplo n.º 36
0
        public void FindPath_WhenPathIsBlockedNavigatesAroundBlocks_ReturnsAdjacentSpacesByShortestPath(int x, int y, decimal expectedMaxDistance)
        {
            _mockMap.Setup(t => t.IsAllowedPosition(new Position(2, 3, 0))).Returns(false);
            _mockMap.Setup(t => t.IsAllowedPosition(new Position(3, 2, 0))).Returns(false);
            _mockMap.Setup(t => t.IsAllowedPosition(new Position(4, 4, 0))).Returns(false);
            var sut = new ShortestPath(_mockMap.Object);
            var results = sut.FindPath(new Position(3, 3, 0), 4);

            var path = results.Single(p => p.EndPosition == new Position(x, y, 0));
            path.PathPositions.ToList().ForEach(p => Debug.WriteLine(p));
            Assert.That(path.Distance, Is.InRange(expectedMaxDistance - 0.25M, expectedMaxDistance));
        }
Ejemplo n.º 37
0
        public void FindPath_WhenPathIsBlocked_DoesNotIncludedBlockedPositions()
        {
            var position = new Position(3, 3, 0);
            _mockMap.Setup(t => t.IsAllowedPosition(position)).Returns(false);
            var sut = new ShortestPath(_mockMap.Object);
            var results = sut.FindPath(position.North(), 3);

            var path = results.SingleOrDefault(t => t.EndPosition == position);
            Assert.That(path, Is.Null);
        }
Ejemplo n.º 38
0
        public void FindPath_WhenDistanceIsTwo_ReturnsTwoAdjacentSpacesAndOneDiagonal()
        {
            var expectedResults = new[]{
                                          new Position(3,1,0),
                                          new Position(3,2,0),
                                          new Position(3,4,0),
                                          new Position(3,5,0),
                                          new Position(1,3,0),
                                          new Position(2,3,0),
                                          new Position(4,3,0),
                                          new Position(5,3,0),
                                          new Position(2,2,0),
                                          new Position(4,2,0),
                                          new Position(4,4,0),
                                          new Position(2,4,0),
                                       };

            var startPosition = new Position(3, 3, 0);
            var sut = new ShortestPath(_mockMap.Object);
            var results = sut.FindPath(startPosition, 2);

            Assert.That(Sort(results.Select(x => x.EndPosition)), Is.EquivalentTo(Sort(expectedResults)));
            results.ToList().ForEach(Console.WriteLine);
        }