矩阵的最小路径和
来源:互联网 发布:mindmanager for mac 编辑:程序博客网 时间:2024/04/20 10:50
public class Solution { public static void main(String[] args) { int[][] array = {{1, 0, 3}, {1, 2, 1}, {2, 0, 1}}; System.out.println("原矩阵: "); Solution.traverseArray(array); System.out.println("矩阵最小路径和为: " + Solution.minPathSum(array)); } /** * 矩阵最小路径和 * * 题目描述:给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。 * * @param grid * @return */ public static int minPathSum(int[][] grid) { if(grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) { return 0; } int row = grid.length; int col = grid[0].length; int[][] dp = new int[row][col]; dp[0][0] = grid[0][0]; // 第一列的处理 for(int i = 1; i < row; i++) { dp[i][0] = dp[i-1][0] + grid[i][0]; } // 第一行的处理 for(int j = 1; j < col; j++) { dp[0][j] = dp[0][j-1] + grid[0][j]; } // 其他行列元素的处理 for(int i = 1; i < row; i++) { for(int j = 1; j < col; j++) { dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; } } // 遍历dp数组 System.out.println("矩阵最小路径和长度矩阵dp: "); Solution.traverseArray(dp); return dp[row-1][col-1]; } public static void traverseArray(int array[][]) { for(int i = 0; i < array.length; i++) { for(int j = 0; j < array[0].length; j++) { System.out.print(" " + array[i][j]); } System.out.println(); } }}
阅读全文
0 0
- 矩阵的最小路径和
- 矩阵的最小路径和
- 矩阵的最小路径和
- 矩阵的最小路径和
- 矩阵的最小路径和
- 矩阵的最小路径和
- 矩阵最小路径和
- 矩阵最小路径和
- 矩阵的最小路径和 [DP]
- 动态规划--矩阵最小的路径和
- 矩阵最小路径和练习
- 矩阵的最小路径之和
- 矩阵的最小路径和(空间压缩)
- 递归与动态规划---矩阵的最小路径和
- 动态规划之矩阵的最小路径和
- 动态规划,矩阵最小路径和
- 矩阵最小路径和(java实现)
- 动态规划--矩阵最小路径和
- 在Android Studio 运行的时候报dalvikvm: Could not find class 'xxx',
- ReactNative中的布局
- Struts2
- Horizontal_ViewPager_Fragment
- C语言 剧情版小游戏
- 矩阵的最小路径和
- PHP 练习题
- 大津算法
- 基于RocketMQ的推送猜想
- javascript继承
- 应用密码学(学习整理、二)
- 【Eclipse】安装Eclipse Color Theme 插件
- sklearn分类器
- B