• [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 }
  • 相关阅读:
    vue--一些预设属性
    vue--vux框架的使用
    vue--vConsole
    vue--音乐播放器
    vue--使用vue-cli构建项目
    vue--实例化对象
    vue--数据显示模版上
    CSS--交互效果
    Git SSH公钥配置
    gradle配置国内镜像
  • 原文地址:https://www.cnblogs.com/lz87/p/7288839.html
Copyright © 2020-2023  润新知