public class Solution {
private int[][] dirs = new int[][] {
{-1, 0},
{1, 0},
{0, -1},
{0, 1}
};
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 递增路径的最大长度
* @param matrix int整型二维数组 描述矩阵的每个数
* @return int整型
*/
public int solve (int[][] matrix) {
// write code here
if (matrix == null || matrix.length < 1 || matrix[0] == null || matrix[0].length < 1) {
return 0;
}
int max = 0;
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n + 1][m + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
max = Math.max(max, dfs(matrix, dp, i, j));
}
}
return max;
}
private int dfs(int[][] matrix, int[][] dp, int i, int j) {
if (dp[i][j] != 0) {
return dp[i][j];
}
dp[i][j]++;
int n = matrix.length;
int m = matrix[0].length;
for (int k = 0; k < 4; k++) {
int row = i + dirs[k][0];
int col = j + dirs[k][1];
if (row >= 0 && row < n && col >= 0 && col < m && matrix[row][col] > matrix[i][j]) {
dp[i][j] = Math.max(dp[i][j], dfs(matrix, dp, row, col) + 1);
}
}
return dp[i][j];
}
}