Min Cost Path

 

Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.

For example, in the following figure, what is the minimum cost path to (2, 2)?

The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).

http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/

下面是递归法和动态规划法的C++程序:

int minCostPath(vector<vector<int>> &cost, int m, int n)
{
if (n < 0 || m < 0) return INT_MAX;
else if (m == 0 && n == 0) return cost[m][n];
else return cost[m][n] + min(minCostPath(cost, m-1, n-1),
min(minCostPath(cost, m-1, n), minCostPath(cost, m, n-1)));
} int minCostPathDP(vector<vector<int> > &cost)
{
int row = cost.size();
if (row < 1) return 0;
int col = cost[0].size(); vector<vector<int> > ta(2, vector<int>(col));
bool flag = false;
ta[!flag][0] = cost[0][0];
for (int i = 1; i < col; i++)
{
ta[!flag][i] = ta[!flag][i-1] + cost[0][i];
} for (int i = 1; i < row; i++)
{
ta[flag][0] = ta[!flag][0] + cost[i][0];
for (int j = 1; j < col; j++)
{
ta[flag][j] = min(min(ta[!flag][j],ta[flag][j-1]),
ta[!flag][j-1]) + cost[i][j];
}
flag = !flag;
}
return ta[!flag][col-1];
}

最新文章

  1. java mkdir()和mkdirs()的区别
  2. Codeforces Beta Round #6 (Div. 2 Only)
  3. Object-c 控制语句
  4. 一名合格QA的基本素养
  5. Headfirst JSP 01 (概述)
  6. ubuntu启动慢
  7. 【POJ】2886 Who Gets the Most Candies?
  8. Majority Element,Majority Element II
  9. 数据库外连接及MySQL实现
  10. 201521123121 《Java程序设计》第2周学习总结
  11. 高精度乘法-17南宁区域赛F -The Chosen One
  12. CSS定位网页中的元素
  13. Win10下安装zio
  14. Linux下安装oracle的过程
  15. STM32F103X datasheet学习笔记---Flexible static memory controller (FSMC)
  16. POJ1860 Currency Exchange【最短路-判断环】
  17. bzoj1613
  18. 51Nod 1009:1009 数字1的数量 (思维)
  19. iFIERO - (一) 宇宙大战 SPACE BATTLE — 场景SCENE、SpriteKit精灵、PARTICLE粒子及背景音乐
  20. [ring3反作弊篇] 基于EBP遍历调用栈及模块名

热门文章

  1. Git -- 基本操作 之 版本回退
  2. python模块之 - subprocess执行unix/linux命令
  3. Linux网卡eth0变成eth1修改方法
  4. vs2013(vs2015) 打开vs2010 找不到此项目类型所基于的应用程序 MVC2 升级 MVC5 不能加载Web项目
  5. linux的awk命令解读
  6. xshell,putty远程连接Linux并使用密钥认证
  7. 【WP8】让TextBox文本支持滑动(Scroll)
  8. 【ML】数据集资源
  9. windows server 2003R2\2008R2\2012\2016 安装【故障转移群集】cluster
  10. 怎么安装ABBYY FineReader