矩阵最长递增路径问题
题目描述:
给定一个整数矩阵matrix,每个位置你可以向左、右、下、上移动,找到其中最长的递增路径。
例如:
matrix =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
返回4
最长路径是[1, 2, 6, 9].
matrix = [
[3,4,5],
[3,2,6],
[2,2,1]
]
返回4
最长路径是[ 2, 4,5, 6]
题目难度:
题目思路:
本题可用三种方法: 暴力递归、记忆搜索、动态规划
思路一: 直接暴力递归求解。
对于每一个位置上的数,其实有四种移动路线,即向上、下、左、右。移动时,只要保证向其他位置可移动(不越界,并保证下一个位置大于当前位置值)即可,求出从当前位置出发的最长递增路径。
最终比较,求出所有位置的最长递增路径。
代码实现:
public static int longest(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int max = 0;
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
max = Math.max(max, process(matrix, row, col)); //获取总的最长递增路径
}
}
return max;
}
private static int process(int[][] matrix, int row, int col) {
//求当前位置最长的递增路径
int path = 1; // 原地不动的长度
if (row > 0 && matrix[row - 1][col] > matrix[row][col]) {
//向上移动时
path = Math.max(path, process(matrix, row - 1, col) + 1);
}
if (col > 0 && matrix[row][col - 1] > matrix[row][col]) {
//向左移动时
path = Math.max(path, process(matrix, row, col - 1) + 1);
}
if