题解 | #矩阵最长递增路径#
矩阵最长递增路径
https://www.nowcoder.com/practice/7a71a88cdf294ce6bdf54c899be967a2
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 递增路径的最大长度
* @param matrix int整型二维数组 描述矩阵的每个数
* @return int整型
*/
// 本题有两种解法
// 1. 使用深度优先遍历,记录长度,通过记录遍历路径来来保证遍历路径唯一。
// 2. 还是使用深度优先遍历,记录也是记录遍历路径,只不过遍历过的路径设置为-1,然后比对pre值
int max = 0;
public int solve (int[][] matrix) {
// write code here
boolean[][] booleans = new boolean[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
dfs(matrix, booleans, i, j, 1);
}
}
return max;
}
public void dfs(int[][] matrix, boolean[][] booleans, int i, int j,
int length) {
max = Math.max(length, max);
if (i >= matrix.length || i < 0) {
return;
}
if (j >= matrix.length || j < 0) {
return;
}
if (i + 1 < booleans.length && !booleans[i + 1][j] &&
matrix[i + 1][j] > matrix[i][j]) {
booleans[i + 1][j] = true;
dfs(matrix, booleans, i + 1, j, length + 1);
booleans[i + 1][j] = false;
}
if (j + 1 < booleans[0].length && !booleans[i][j + 1] &&
matrix[i][j + 1] > matrix[i][j]) {
booleans[i][j + 1] = true;
dfs(matrix, booleans, i, j + 1, length + 1);
booleans[i][j + 1] = false;
}
if (j - 1 >= 0 && (!booleans[i][j - 1]) && matrix[i][j - 1] > matrix[i][j]) {
booleans[i][j - 1] = true;
dfs(matrix, booleans, i, j - 1, length + 1);
booleans[i][j - 1] = false;
}
if (i - 1 >= 0 && !booleans[i - 1][j] && matrix[i - 1][j] > matrix[i][j]) {
booleans[i - 1][j] = true;
dfs(matrix, booleans, i - 1, j, length + 1);
booleans[i - 1][j] = false;
}
return;
}
}
查看16道真题和解析