[leetcode]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:

1
2
3
4
5
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

1
2
3
4
5
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.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class  {

public static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

public int longestIncreasingPath(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int row = matrix.length, col = matrix[0].length;
int max = 1;
int[][] cache = new int[row][col];
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
int len = dfs(matrix, i, j, row, col, cache);
max = Math.max(max, len);
}
}

return max;
}

//深度搜索从[i][j]出发的最长递增路径的长度
//cache缓存,即备忘录
public int dfs(int[][] matrix, int i, int j, int row, int col, int[][] cache){
//已经搜索过,直接返回
if(cache[i][j] != 0) return cache[i][j];
int max = 1;
//四个方向搜索
for(int[] dir : dirs){
int x = i + dir[0], y = j + dir[1];
//matrix[x][y] <= matrix[i][j]可以避免使用visited[row][col]数组
if(x < 0 || x >= row || y < 0 || y >= col || matrix[x][y] <= matrix[i][j]) continue;
int len = 1 + dfs(matrix, x, y, row, col, cache);
max = Math.max(len, max);
}

cache[i][j] = max;
return max;
}
}