Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 23, 2013 06:00
Show Gist options
  • Select an option

  • Save riyadparvez/6060191 to your computer and use it in GitHub Desktop.

Select an option

Save riyadparvez/6060191 to your computer and use it in GitHub Desktop.
Minimum cost to reach a grid using dynamic programming in C#.
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