Geeks面试题:Min Cost Path
2014-01-06 07:54
330 查看
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. Totalcost 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] ; else return cost[m] + 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]; }
相关文章推荐
- Geeks面试题:Min Cost Path
- DP6 最小路径花费 Min Cost Path @geeksforgeeks
- Min Cost Path
- 动态规划之最小带权路径(Min Cost Path)
- [DP]Min Cost Path
- Min Cost Path
- hdu 1599 find the mincost route
- HDU 1599 find the mincost route(Floyd判最小环)
- hdu-1599-find the mincost route(弗洛伊德 最小环)
- hdu 1599 find the mincost route(找无向图最小环)(floyd求最小环)
- 【剑指Offer学习】【面试题21:包括min 函数的栈】
- find the mincost route
- Min Cost Climbing Stairs问题及解法
- LeetCode#746 Min Cost Climbing Stairs (week16)
- week16-leetcode #746-MinCostClimbingStairs
- HDU 1599 find the mincost route(无向图最小环)
- HDU 1599 find the mincost route(floyd改/找最小环)
- 微软面试题解题笔记——包含min 函数的栈
- [LeetCode] Minmum Path Sum
- Leetcode747 Min Cost Climbing Stairs(爬楼梯的最小代价)