[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 }

 

转载于:https://www.cnblogs.com/lz87/p/7288839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值