329. Longest Increasing Path in a Matrix
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
为了避免搜索已经搜索的点。所以考虑用一个cache数组,记录到每一个点能产生的最长序列的长度。
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0)
return 0;
int max = 1;
int rows = matrix.length;
int cols = matrix[0].length;
int[][] cache = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
max = Math.max(max, dfs(matrix, i, j, cache));
return max;
}
// 记忆化搜索算法+DFS,cache记忆化数组
private int dfs(int[][] matrix, int row, int col, int[][] cache) {
// 改进:记录下每一个访问过的点的最大长度,当重新访问到这个点的时候,就不需要重复计算
if (cache[row][col] != 0)
return cache[row][col];
// 最小为1,一个点也是
int val = 1;
if (row + 1 < matrix.length && matrix[row + 1][col] > matrix[row][col]) {
// 这里当前结点只算长度1,然后加上dfs后子路径的长度,比较得出最大值
val = Math.max(1 + dfs(matrix, row + 1, col, cache), val);
}
if (row - 1 >= 0 && matrix[row - 1][col] > matrix[row][col]) {
val = Math.max(1 + dfs(matrix, row - 1, col, cache), val);
}
if (col + 1 < matrix[0].length && matrix[row][col + 1] > matrix[row][col]) {
val = Math.max(1 + dfs(matrix, row, col + 1, cache), val);
}
if (col - 1 >= 0 && matrix[row][col - 1] > matrix[row][col]) {
val = Math.max(1 + dfs(matrix, row, col - 1, cache), val);
}
cache[row][col] = val;
return val;
}
定义方向数组
private int dfs(int[][] matrix, int row, int col, int[][] cache) {
if (cache[row][col] != 0)
return cache[row][col];
// 定义一个方向数组,避免写重复代码
int[][] dir = { { 1, 0 }, { -1, 0 },
{ 0, 1 }, { 0, -1 } };
// 定义val是0还是1要和下面调用函数dfs是否+1,和结果返回哪个,要对应
int val = 0;
for (int k = 0; k < dir.length; k++) {
int x = row + dir[k][0];
int y = col + dir[k][1];
if (x >= matrix.length || x < 0
|| y >= matrix[0].length || y < 0)
continue;
else if (matrix[x][y] > matrix[row][col])
val = Math.max(dfs(matrix, x, y, cache), val);
}
cache[row][col] = val + 1;
return cache[row][col];
}