8000 2020/02/22 · freezeYe/leetcode-js@cb997ce · GitHub
[go: up one dir, main page]

Skip to content

Commit cb997ce

Browse files
author
bohrzhang
committed
2020/02/22
1 parent 90e60e5 commit cb997ce

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

329.矩阵中的最长递增路径.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
### 描述:
2+
给定一个整数矩阵,找出最长递增路径的长度。
3+
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
4+
5+
### 示例:
6+
```
7+
示例 1:
8+
输入: nums =
9+
[
10+
[9,9,4],
11+
[6,6,8],
12+
[2,1,1]
13+
]
14+
输出: 4
15+
解释: 最长递增路径为 [1, 2, 6, 9]。
16+
17+
示例 2:
18+
输入: nums =
19+
[
20+
[3,4,5],
21+
[3,2,6],
22+
[2,2,1]
23+
]
24+
输出: 4
25+
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
26+
```
27+
28+
### 解析:
29+
一道典型的动态规划问题,设record[x][y]为以x,y为终点的最长路径,依次遍历其上下左右4个节点a,b, 当matrix[a][b]满足递增条件时record[x][y]=max(record[x][y], dp(a,b)+1),对于已经遍历过得节点直接返回当前最长路径值。
30+
31+
时间复杂度: O(mn) / 空间复杂度: O(mn)
32+
33+
```javascript
34+
/**
35+
* @param {number[][]} matrix
36+
* @return {number}
37+
*/
38+
var longestIncreasingPath = function(matrix) {
39+
if(!matrix.length) return 0
40+
let max = 0
41+
const row = matrix.length
42+
const column = matrix[0].length
43+
const track = [{x: -1,y: 0}, {x: 1, y: 0}, {x: 0, y: -1}, {x: 0,y: 1}]
44+
const record = new Array(row).fill(0).map(i=> new Array(column).fill(0))
45+
const dp = (i, j)=> {
46+
if(record[i][j] !== 0) return record[i][j]
47+
record[i][j] = 1
48+
track.forEach(point=> {
49+
const dx = i + point.x
50+
const dy = j + point.y
51+
if(dx >= 0 && dy >= 0 && dx < row && dy < column && matrix[dx][dy] > matrix[i][j]) {
52+
record[i][j] = Math.max(record[i][j], dp(dx, dy) + 1)
53+
}
54+
})
55+
return record[i][j]
56+
}
57+
for(let i=0; i<row; i++) {
58+
for(let j=0; j<column; j++) {
59+
max = Math.max(max, dp(i, j))
60+
}
61+
}
62+
return max
63+
};
64+
```

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@
22

33
[1. 两数之和(简单)](./1.两数之和.md)
44

5-
[2. 两数相加(中等)](./2.两数相加.md)
5+
[2. 两数相加(中等)](./2.两数相加.md)
6+
7+
[329. 矩阵中的最长递增路径(困难)](./329.矩阵中的最长递增路径.md)

0 commit comments

Comments
 (0)
0