码迷,mamicode.com
首页 > 其他好文 > 详细

[Coding Made Simple] Minimum Cost Path

时间:2017-08-26 10:12:34      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:==   rom   nbsp   cost   div   class   simple   get   down   

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

标签:==   rom   nbsp   cost   div   class   simple   get   down   

原文地址:http://www.cnblogs.com/lz87/p/7288839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!