Skip to content

Commit 762c188

Browse files
authored
Update 329-longest-increasing-path-in-a-matrix.js
1 parent bc1cbed commit 762c188

File tree

1 file changed

+34
-23
lines changed

1 file changed

+34
-23
lines changed

329-longest-increasing-path-in-a-matrix.js

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,43 @@
22
* @param {number[][]} matrix
33
* @return {number}
44
*/
5-
const longestIncreasingPath = function(matrix) {
6-
if (matrix.length === 0) return 0
7-
let max = 1
8-
const rows = matrix.length
9-
const cols = matrix[0].length
10-
const cache = Array.from({ length: rows }, () => new Array(cols).fill(0))
11-
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
12-
for (let i = 0; i < rows; i++) {
13-
for (let j = 0; j < cols; j++) {
14-
let len = dfs(matrix, i, j, rows, cols, cache, dirs)
15-
max = Math.max(max, len)
5+
const longestIncreasingPath = function (matrix) {
6+
const dirs = [
7+
[-1, 0],
8+
[1, 0],
9+
[0, -1],
10+
[0, 1],
11+
]
12+
const m = matrix.length,
13+
n = matrix[0].length
14+
let res = 1
15+
const memo = Array.from({ length: m }, () => Array(n).fill(0))
16+
for (let i = 0; i < m; i++) {
17+
for (let j = 0; j < n; j++) {
18+
const tmp = dfs(matrix, i, j, m, n, memo, dirs)
19+
res = Math.max(tmp, res)
1620
}
1721
}
18-
return max
22+
return res
1923
}
2024

21-
function dfs(matrix, i, j, rows, cols, cache, dirs) {
22-
if (cache[i][j] !== 0) return cache[i][j]
23-
let max = 1
24-
for (let dir of dirs) {
25-
let ii = i + dir[0]
26-
let jj = j + dir[1]
27-
if (ii < 0 || ii >= rows || jj < 0 || jj >= cols || matrix[ii][jj] <= matrix[i][j]) continue
28-
let len = 1 + dfs(matrix, ii, jj, rows, cols, cache, dirs)
29-
max = Math.max(len, max)
25+
function dfs(matrix, i, j, m, n, memo, dirs) {
26+
if (memo[i][j] !== 0) return memo[i][j]
27+
let res = 1
28+
for (let [dx, dy] of dirs) {
29+
const nx = i + dx,
30+
ny = j + dy
31+
if (
32+
nx < 0 ||
33+
nx >= m ||
34+
ny < 0 ||
35+
ny >= n ||
36+
matrix[nx][ny] <= matrix[i][j]
37+
)
38+
continue
39+
const tmp = 1 + dfs(matrix, nx, ny, m, n, memo, dirs)
40+
res = Math.max(res, tmp)
3041
}
31-
cache[i][j] = max
32-
return max
42+
memo[i][j] = res
43+
return res
3344
}

0 commit comments

Comments
 (0)