-2

I have to start at location (0,0) and I can either move up or move right (no diagonal traversals). I need the minimum cost matrix to reach node (n-1,n-1). I also need the recorded path for the minimum cost. Also, I need to count the total number of paths to the destination node(n-1,n-1).

For eg.

Matrix:
7 9 2
1 5 8
2 3 7

Output:
Min cost path: 2 -> 1 -> 5 -> 8 -> 2
Sum(Min Cost Path excluding the ending node): 16
Total number of paths: 6
ExeCode
  • 21
  • 1
  • 6
  • This sounds like you just typed a question from a homework assignment - provide code that you have written or at least show something that indicates you have put in some effort to solve this yourself, and also ask a specific question that can answered without completing your assignment for you. – Matt Jordan Apr 01 '16 at 03:26

1 Answers1

0

First of all, your question has some errors. " I have to start at location (0,0) and I can either move up or move right.". I think it should be down or right.

That is from (i,j) you can move to (i,j+1) and (i+1,j).

The recursive formula will be

minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]

The time complexity for this will be exponential as same sub problem is computed many times and this will continue for each cell.

To cover up on time complexity, you can do this using dynamic programming.

Create a temp table in a bottom up manner to store the results of the sub problem so that we do not need to compute again. In simple terms i,j index of the temp table will store the minimum cost path from 0,0 to i,j. The time complexity is reduced to O(nm). I can't give the whole code to you as it seems to be a homework question.

On your second question which is to find the total paths. There will be only one minimum cost path. Or if you want to find all the paths.

FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
  • No this is exactly why I posted the question here. It's not down and right but up and right. (0,0) is being visualized as the bottom left of the matrix so this would actually map to location (n-1,0). I devised the solution, thanks anyways. – ExeCode Apr 14 '16 at 09:35