p329

LeetCode p329 Longest Increasing Path in a Matrix 题解

1.题目:

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.

题意:

给一个二维数组,求其内部可以连成的最长递增路径。
可与上下左右相连。

2.解题思路:

dfs 将每一点作为起点开始搜索,不过这样会超时。
所以设立缓存的数组dfs[][],进行储存。

3.代码


[title] [] [url] [link text]
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
 
public class Solution {
public int longestIncreasingPath(int[][] matrix) {

int ans = 0;
int[][] dfs;
if (matrix.length < 1)
return 0;
dfs = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
dfs[i][j] = -1;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
ans = Math.max(
ans,
longestIncreasingPath(matrix, i, j, dfs,
Integer.MIN_VALUE));
// System.out.println(i + " " + j + " " + dfs[i][j]);
}
}
return ans ;

}

public static int longestIncreasingPath(int[][] matrix, int i, int j,
int[][] dfs, int a) {
if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length
|| a >= matrix[i][j]) {
return 0;
}
if (dfs[i][j] > -1) {

// System.out.println("----------"+dfs[i][j]+"i:"+i+" "+j);

return dfs[i][j];
}
int c = 0;
// up

// System.out.println(c);
c = Math.max(c,
longestIncreasingPath(matrix, i - 1, j, dfs, matrix[i][j]) + 1);

// down

c = Math.max(c,
longestIncreasingPath(matrix, i + 1, j, dfs, matrix[i][j]) + 1);

// left

c = Math.max(c,
longestIncreasingPath(matrix, i, j - 1, dfs, matrix[i][j]) + 1);

// right

c = Math.max(c,
longestIncreasingPath(matrix, i, j + 1, dfs, matrix[i][j]) + 1);

dfs[i][j] = c;
return c;
}
}

4.一些总结: