题解 | #矩阵最长递增路径 与岛屿数量一致#
矩阵最长递增路径
http://www.nowcoder.com/practice/7a71a88cdf294ce6bdf54c899be967a2
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 递增路径的最大长度
* @param matrix int整型二维数组 描述矩阵的每个数
* @return int整型
*/
public int solve (int[][] matrix) {
// write code here
int n = matrix.length;
int m = matrix[0].length;
int maxRes = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int temp = process(matrix, i, j, -1);
maxRes = temp > maxRes ? temp : maxRes;
}
}
return maxRes;
}
public static int process(int[][] matrix, int i, int j, int pre){
if (i < 0 || i >= matrix.length ||
j < 0 || j >= matrix.length ||
matrix[i][j] <= pre) {
return 0;
}
int max = 0;
max = Math.max(process(matrix, i - 1, j, matrix[i][j]), max);
max = Math.max(process(matrix, i + 1, j, matrix[i][j]), max);
max = Math.max(process(matrix, i, j - 1, matrix[i][j]), max);
max = Math.max(process(matrix, i, j + 1, matrix[i][j]), max);
return max + 1;
}
}