Longest Increasing Path in a Matrix LeetCode solution in JavaScript

1
var longestIncreasingPath = function (matrix) {
2
const m = matrix.length,
3
n = matrix[0].length;
4
const dp = new Array(m).fill(0).map(() => {
5
return new Array(n).fill(-1);
6
});
7

8
let ans = 0;
9
const dir = [0, -1, 0, 1, 0];
10

11
const dfs = (x, y) => {
12
if (dp[x][y] != -1) return dp[x][y];
13

14
for (let i = 1; i <= 4; i++) {
15
const [nx, ny] = [x + dir[i], y + dir[i - 1]];
16
if (
17
nx >= 0 &&
18
ny >= 0 &&
19
nx < m &&
20
ny < n &&
21
matrix[nx][ny] > matrix[x][y]
22
) {
23
dp[x][y] = Math.max(dp[x][y], 1 + dfs(nx, ny));
24
}
25
}
26

27
if (dp[x][y] == -1) dp[x][y] = 1;
28
ans = Math.max(ans, dp[x][y]);
29
return dp[x][y];
30
};
31

32
for (let i = 0; i < m; i++) {
33
for (let j = 0; j < n; j++) {
34
if (dp[i][j] == -1) dfs(i, j);
35
}
36
}
37

38
return ans;
39
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0