LeetCode 329 longest increasing path in a matrix
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down.
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
这道题乍一看上去 就像是LIS LCS问题,但是因为可以往上下左右移动 所以这有点像DP题目
而且这道题有点像flood fill的问题 从任何一点出发都能前后左右的走。
这道题结合了DFS和DP
这是我自己写的:(无法AC)
class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0) return 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m][n];
//dp[i][j] represents for the the LIP starting in the position of (i,j)
int res = Integer.MIN_VALUE;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res = Math.max(res, dfs(matrix, i, j, dp));
}
}
return res;
}
private int dfs(int[][] matrix, int i, int j, int[][] dp) {
if (!inBound(matrix, i, j)) {
return 0;
}
int[][] direction = new int[][]{{1,0},{-1, 0}, {0, 1}, {0, -1}};
dp[i][j] = 1; //初始化这个 很重要 经常忘记
//we get hte max of dp[i][j] from those four directions
for (int k = 0; k < 4; k++) {
if (inBound(matrix, i + direction[k][0], j + direction[k][1]) && (matrix[i + direction[k][0]][j + direction[k][1]] > matrix[i][j])) { //this is what we have to obey and don't forget that
dp[i][j] = Math.max(dp[i][j],dfs(matrix, i + direction[k][0], j + direction[k][1], dp) + 1);
}
}
return dp[i][j];
}
private boolean inBound(int[][] matrix, int i, int j) {
int m = matrix.length;
int n = matrix[0].length;
if (i < 0 || i >= m || j < 0 || j >= n) {
return false;
}
return true;
}
}
这是我之前写的,能够AC
上下两个代码几乎一样 但是上面的就是有问题 实在想不明白。
class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m][n];
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res = Math.max(res, dfs(matrix, i, j, dp));
}
}
return res;
}
private int dfs(int[][] matrix, int i, int j, int[][] dp) { //the max increasing length starting from position[i,j]
if (dp[i][j] != 0) return dp[i][j]; //memo //and this is super important, without this, we will have a TLE
//why this work is based on once we modify dp[i][j], it must be the final results of this position and no futher modification
int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
dp[i][j] = 1;
for (int k = 0; k < 4; k++) {
if (inBound(matrix, i + direction[k][0], j + direction[k][1]) && (matrix[i + direction[k][0]][j + direction[k][1]] > matrix[i][j])) {
dp[i][j] = Math.max(dp[i][j], 1 + dfs(matrix, i + direction[k][0], j + direction[k][1], dp));
}
}
return dp[i][j];
}
private boolean inBound(int[][] matrix, int i, int j) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int m = matrix.length;
int n = matrix[0].length;
if (i < 0 || i >= m || j < 0 || j >= n) {
return false;
}
return true;
}
}

浙公网安备 33010602011771号