package leetcode;
/**
* 329. 矩阵中的最长递增路径
* 给定一个 m x n 整数矩阵 matrix ,找出其中 最长递增路径 的长度。
* <p>
* 对于每个单元格,你可以往上,下,左,右四个方向移动。 你 不能 在 对角线 方向上移动或移动到 边界外(即不允许环绕)。
* <p>
* <p>
* <p>
* 示例 1:
* <p>
* <p>
* 输入:matrix = [[9,9,4],[6,6,8],[2,1,1]]
* 输出:4
* 解释:最长递增路径为 [1, 2, 6, 9]。
* 示例 2:
* <p>
* <p>
* 输入:matrix = [[3,4,5],[3,2,6],[2,2,1]]
* 输出:4
* 解释:最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
* 示例 3:
* <p>
* 输入:matrix = [[1]]
* 输出:1
* <p>
* <p>
* 提示:
* <p>
* m == matrix.length
* n == matrix[i].length
* 1 <= m, n <= 200
* 0 <= matrix[i][j] <= 231 - 1
* 通过次数44,631提交次数94,509
*/
public class longestIncreasingPath {
public static int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int[][] dp = new int[matrix.length][matrix[0].length];
// dp[i][j] (i,j)出发,走出的最大链长度
int max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
//每一个(i,j)位置出发,都尝试
max = Math.max(max, maxIncrease(matrix, dp, i + 1, j, matrix[i][j]) + 1);
max = Math.max(max, maxIncrease(matrix, dp, i, j + 1, matrix[i][j]) + 1);
max = Math.max(max, maxIncrease(matrix, dp, i - 1, j, matrix[i][j]) + 1);
max = Math.max(max, maxIncrease(matrix, dp, i, j - 1, matrix[i][j]) + 1);
}
}
return max;
}
//来到的当前位置是i,j位置
// p 上一步值是什么
// 从(i,j)位置出发,走出的最长链,要求:上一步是可以迈到当前步上的
public static int maxIncrease(int[][] m, int[][] dp, int i, int j, int p) {
if (i < 0 || i >= m.length || j < 0 || j >= m[0].length || m[i][j] <= p) {
return 0;
}
if (dp[i][j] == 0) {//i,j 出发 当前没算过
dp[i][j] = maxIncrease(m, dp, i + 1, j, m[i][j]) + 1;
dp[i][j] = Math.max(dp[i][j], maxIncrease(m, dp, i, j + 1, m[i][j]) + 1);
dp[i][j] = Math.max(dp[i][j], maxIncrease(m, dp, i - 1, j, m[i][j]) + 1);
dp[i][j] = Math.max(dp[i][j], maxIncrease(m, dp, i, j - 1, m[i][j]) + 1);
}
return dp[i][j];
}
public static int longestIncreasingPath2(int[][] matrix) {
int ans = 0;
int[][] dp = new int[matrix.length][matrix[0].length];
// dp[i][j] (i,j)出发,走出的最大链长度
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
//每一个(i,j)位置出发,都尝试
ans = Math.max(ans, process(matrix, i, j, dp));
}
}
return ans;
}
private static int process(int[][] matrix, int i, int j, int[][] dp) {
if (dp[i][j] != 0) {
return dp[i][j];
}
int up = i > 0 && matrix[i][j] < matrix[i - 1][j] ? process(matrix, i - 1, j, dp) : 0;
int down = i < (matrix.length - 1) && matrix[i][j] < matrix[i + 1][j] ? process(matrix, i + 1, j, dp) : 0;
int left = j > 0 && matrix[i][j] < matrix[i][j - 1] ? process(matrix, i, j - 1, dp) : 0;
int right = j < (matrix[0].length - 1) && matrix[i][j] < matrix[i][j + 1] ? process(matrix, i, j + 1, dp) : 0;
int ans = Math.max(Math.max(up, down), Math.max(left, right)) + 1;
dp[i][j] = ans;
return ans;
}
}
leetcode 329. 矩阵中的最长递增路径
最新推荐文章于 2023-02-27 10:46:52 发布
本文探讨了如何使用动态规划解决LeetCode中的329题——矩阵中的最长递增路径问题。通过实例展示了两种不同的求解方法,并强调了遍历边界和状态转移的重要性。
828





