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

 

posted @ 2017-08-26 06:47  Review->Improve  阅读(221)  评论(0编辑  收藏  举报