|
2 | 2 | * @param {number[][]} matrix
|
3 | 3 | * @return {number}
|
4 | 4 | */
|
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) |
16 | 20 | }
|
17 | 21 | }
|
18 |
| - return max |
| 22 | + return res |
19 | 23 | }
|
20 | 24 |
|
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) |
30 | 41 | }
|
31 |
| - cache[i][j] = max |
32 |
| - return max |
| 42 | + memo[i][j] = res |
| 43 | + return res |
33 | 44 | }
|
0 commit comments