C# – Finding lowest cost path – dynamic

cdynamic programming

I have to write a dynamic algorithm for finding lowest cost path. So I have a point that I have to visit. I can jump only between points by distance – 5 I have an array of distance from 0-point for example (1 3 5 10 15 20 21 22). Each move cost me 1. So the best path will be to move 1->5->15->20->22 (3 and 21 I can skip).

Can you give me so hints, how to program it dynamically? I was thinking to make something like this: Find the solution for array[0] and array[1] (that's easy there is only one solution from to 1 (1->3)) then add array[2], and find the best solution (1->5 also there is a solution 1->3->5 but that's going to cost me 2 moves) then for 4 points, 5 etc.

But don't know how to start to make my algorithm to be written correct and dynamic. I know I can make greedy algorithm, but that's not the point of the task… Can you give me any hints? How to start? How to keep solutions? and find the best ones?

Best Answer

Another approach (graph search):

Graph

Step 1: Parse initial data

Consider each point is a node of and each possible move is a path between two nodes.

Create a N*N matrix(graph) and compute the path value between each nodes.

  • path(A,B) = 1 : if abs(nodeA - nodeB) <= 5

else

  • path(A,B) = MAXINT

Example

Step 2: Compute the shortest path

Apply a fast graph search algorithm (eg: Dijkstra's algorithm) to your matrix.