Finding the shortest path in a graph without any negative prefixes

后端 未结 9 1949
北荒
北荒 2021-01-31 11:15

Find the shortest path from source to destination in a directed graph with positive and negative edges, such that at no point in the path the sum of edges coming

9条回答
  •  时光取名叫无心
    2021-01-31 11:37

    I would use recursion brute forcing here: something like (pseudo code to make sure it's not language specific)

    you will need:

    • 2D array of bools showing where you CAN and where you CAN'T go, this should NOT include "forbidden values", like before negative edge, you can choose to add a vertical and horizontal 'translation' to make sure it starts at [0][0]
    • an integer (static) containing the shortest path
    • a 1D array of 2 slots, showing the goal. [0] = x, [1] = y

    you will do:

    function(int xPosition, int yPosition, int steps)
    {
    if(You are at target AND steps < Shortest Path)
        Shortest Path = steps
    if(This Position is NOT legal)
        /*exit function*/
    else
        /*try to move in every legal DIRECTION, not caring whether the result is legal or not
        but always adding 1 to steps, like using:*/
        function(xPosition+1, yPosition, steps+1);
        function(xPosition-1, yPosition, steps+1);
        function(xPosition, yPosition+1, steps+1);
        function(xPosition, yPosition-1, steps+1);
    }
    

    then just run it with function(StartingX, StartingY, 0);

    the shortest path will be contained in the static external int

提交回复
热议问题