Created
July 23, 2013 06:00
-
-
Save riyadparvez/6060191 to your computer and use it in GitHub Desktop.
Minimum cost to reach a grid using dynamic programming in C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static double MinCost(double[,] cost, int m, int n) | |
| { | |
| double[,] totalCost = new double[m+1, n+1]; | |
| totalCost[0, 0] = cost[0, 0]; | |
| for (int i = 1; i <= m; i++) | |
| { | |
| totalCost[i, 0] = totalCost[i-1, 0] + cost[i, 0]; | |
| } | |
| for (int i = 1; i <= n; i++) | |
| { | |
| totalCost[0, i] = totalCost[0, i-1] + cost[0, i]; | |
| } | |
| for (int i = 2; i <= m; i++) | |
| { | |
| for (int j = 2; j <= n; j++) | |
| { | |
| totalCost[i, j] = Min(Min(totalCost[i-1, j], totalCost[i, j-1]), totalCost[i-1, j-1]) | |
| + cost[i, j]; | |
| } | |
| } | |
| return totalCost[m, n]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment