[Coding Made Simple] Minimum Cost Path

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Coding Made Simple] Minimum Cost Path相关的知识,希望对你有一定的参考价值。

Given a 2 dimensional matrix, find minimum cost path to reach bottom right from top left provided you can only from down and right.

 

For a 5 * 5 matrix, think of solving this problem by breaking it into smaller subproblems. And overlapping subproblems is clear.

                    (4, 4)

          (4, 3)                    (3,4)

      (4, 2)      (3,3)            (3,3)      (2,4)

 

 1 public int getMinPathCost(int[][] matrix) {
 2     if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
 3         return 0;
 4     }
 5     int[][] cost = new int[matrix.length][matrix[0].length];
 6     cost[0][0] = matrix[0][0];
 7     for(int i = 1; i < cost.length; i++) {
 8         cost[i][0] = cost[i - 1][0] + matrix[i][0];
 9     }
10     for(int j = 1; j < cost[0].length; j++) {
11         cost[0][j] = cost[0][j - 1] + matrix[0][j];
12     }
13     for(int i = 1; i < cost.length; i++) {
14         for(int j = 1; j < cost[0].length; j++) {
15             cost[i][j] = Math.min(cost[i][j - 1], cost[i - 1][j]) + matrix[i][j];
16         }
17     }
18     return cost[cost.length - 1][cost[0].length - 1];
19 }

 

以上是关于[Coding Made Simple] Minimum Cost Path的主要内容,如果未能解决你的问题,请参考以下文章

[Coding Made Simple] Longest Increasing Subsequence

[Coding Made Simple] String Interleaving

[Coding Made Simple] Matrix Chain Multiplication

[Coding Made Simple] Burst Balloon

[Coding Made Simple] Subset Sum Problem

[Coding Made Simple] Minimum Cost Path