Skip to content

Commit ed30099

Browse files
committed
《程序代码面试指南》 已完成 递归和动态规划-矩阵的最小路径和
1 parent e2248b8 commit ed30099

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package zuochengyun.recursion_dp;
2+
3+
/**
4+
* @Description 矩阵的最小路径和 https://leetcode.cn/problems/0i0mDW/
5+
* @Author 爱做梦的鱼
6+
* @Blog https://zihao.blog.csdn.net/
7+
* @Date 2023/5/17 16:21
8+
*/
9+
public class minPathSumOfMatrix {
10+
11+
public int getMinPathSum(int[][] matrix) {
12+
int m = matrix.length;
13+
int n = matrix[0].length;
14+
int[][] dp = new int[m][n];
15+
dp[0][0] = matrix[0][0];
16+
for (int i = 1; i < m; i++) {
17+
dp[i][0] = dp[i - 1][0] + matrix[i][0];
18+
}
19+
for (int j = 1; j < n; j++) {
20+
dp[0][j] = dp[0][j - 1] + matrix[0][j];
21+
}
22+
for (int i = 1; i < m; i++) {
23+
for (int j = 1; j < n; j++) {
24+
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + matrix[i][j];
25+
}
26+
}
27+
return dp[m - 1][n - 1];
28+
}
29+
30+
//给定一个矩阵 m,从左上角开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,返回所有的路径中最小的路径和。
31+
// 贪心算法
32+
public int getMinPathSum1(int[][] matrix) {
33+
return dfs(matrix, 0, 0, matrix[0][0]);
34+
}
35+
36+
public int dfs(int[][] matrix, int i, int j, int result) {
37+
System.out.println(i + " " + j);
38+
int m = matrix.length;
39+
int n = matrix[0].length;
40+
if (i == m - 1 && j == n - 1) {
41+
return result;
42+
}
43+
if (i == m - 1) {
44+
return dfs(matrix, i, j + 1, result + matrix[i][j + 1]);
45+
}
46+
if (j == n - 1) {
47+
return dfs(matrix, i + 1, j, result + matrix[i + 1][j]);
48+
}
49+
if (matrix[i + 1][j] < matrix[i][j + 1]) {
50+
return dfs(matrix, i + 1, j, result + matrix[i + 1][j]);
51+
} else {
52+
return dfs(matrix, i, j + 1, result + matrix[i][j + 1]);
53+
}
54+
}
55+
56+
public static void main(String[] args) {
57+
int[][] matrix = new int[][]{{1, 3, 5, 9}, {8, 1, 3, 4}, {5, 0, 6, 1}, {8, 8, 4, 0}};
58+
int result = new minPathSumOfMatrix().getMinPathSum(matrix);
59+
System.out.println(result);
60+
}
61+
62+
}

0 commit comments

Comments
 (0)