题解 | #矩阵最长递增路径#
矩阵最长递增路径
http://www.nowcoder.com/practice/7a71a88cdf294ce6bdf54c899be967a2
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 递增路径的最大长度
* @param matrix int整型二维数组 描述矩阵的每个数
* @return int整型
*/
public int solve (int[][] matrix) {
// write code here
int rs = Integer.MIN_VALUE;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
rs = Math.max(rs, process(matrix, i, j, Integer.MIN_VALUE, 0));
}
}
return rs;
}
public int process(int[][] matrix, int i, int j, int val, int rs) {
if (i < 0 || i > matrix.length - 1 || j < 0 || j > matrix[0].length - 1 || matrix[i][j] == -1 || matrix[i][j] <= val) {
return rs;
}
int tmp = matrix[i][j];
matrix[i][j] = -1;
rs += 1;
int ur = process(matrix, i, j - 1, tmp, rs);
int dr = process(matrix, i, j + 1, tmp, rs);
int lr = process(matrix, i - 1, j, tmp, rs);
int rr = process(matrix, i + 1, j, tmp, rs);
matrix[i][j] = tmp;
return Math.max(rr, Math.max(lr, Math.max(ur, dr)));
}
}