Cheapest path algorithm

后端 未结 7 1758
刺人心
刺人心 2020-12-20 03:28

I\'ve learnt a dynamic programming algorithm to find the \"cheapest\" path from A to B. Each sub path has an associated cost.

Each corner is calculated using

7条回答
  •  天涯浪人
    2020-12-20 04:01

    Looks like you are working with a graph where the nodes are points on a 2D grid and each node has a directed edge to the node above it and another to the node to its right.

    I don't think just applying Dijkstra's algorithm will work here. It finds one cheapest cost path, and there is really no way to modify it to find all shortest paths.

    Since this is such a special graph (i.e. directed and acyclic), you can compute the number of cheapest paths, provided you know what the cost of the cheapest path is, using a simple recurrence. Notice that

    number_paths(i,j)=number_of_paths(i-1,j)+number_of_paths(i,j-1)
    

    i.e. the number of paths from any node is the sum of that from the nodes above and to its right. (This omits the base cases where the current node is the destination and where the destination node is unreachable from the current node.)

    The only thing needed is to modify this to count only those paths that are cheapest. Now, we already know that the cheapest path has some cost X. We can use it to augment our recurrence so that it only counts the cheapest path. At the start node, we know that the cost of the remaining path is X. From any of the adjacent nodes to the start node (i.e. from the nodes directly above and right of it), the cost is therefore X-e, where e is the cost of the edge between those nodes. This rule applies to any node where the cost to reach the current node is known. Thus we know we have traversed a cheapest path when we reach the destination node and the value of that node is 0 (i.e. we have subtracted all the costs of the edges that form a cheapest path).

    So we can just augment our recurrence so that we keep 3 values instead of 2, the coordinates and the remaining cost of the path (essentially converting into the same problem for a 3D graph, where the 3rd dimension is cost). The start node is of the form (x_start,y_start,cost), the destination node is of the form (x_end,y_end,0). Our recurrence would look like:

    paths(x,y,cost_left)=
                     0         if x_end,y_end is unreachable from x,y or cost_left<0
                     1         if x==X-end and y==y_end and cost_left==0
                     paths(x-1,y,cost_left-edge(x,y,x-1,y))+paths(x,y-1,cost_left-edge(x,y,x,u-1))   otherwise
    

    The complexity of the algorithm should be O(nmC) where n and m are the dimensions of the grid and C is the cost of the cheapest path.

提交回复
热议问题