Skip to content

Commit e7722e5

Browse files
authored
Merge pull request neetcode-gh#769 from kciccolella/leetcode329
Create 329-Longest-Increasing-Path-in-a-Matrix.js
2 parents eaa74f5 + 3475e67 commit e7722e5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number}
4+
*/
5+
var longestIncreasingPath = function(matrix) {
6+
const ROWS = matrix.length;
7+
const COLS = matrix[0].length;
8+
const dp = {}; // r|c -> LIP
9+
10+
function dfs(r, c, prevVal) {
11+
if (r < 0 || r === ROWS ||
12+
c < 0 || c === COLS ||
13+
matrix[r][c] <= prevVal) {
14+
return 0;
15+
}
16+
17+
if (dp.hasOwnProperty(`${r}|${c}`)) {
18+
return dp[`${r}|${c}`];
19+
}
20+
21+
let res = 1;
22+
res = Math.max(res, 1 + dfs(r + 1, c, matrix[r][c]));
23+
res = Math.max(res, 1 + dfs(r - 1, c, matrix[r][c]));
24+
res = Math.max(res, 1 + dfs(r, c + 1, matrix[r][c]));
25+
res = Math.max(res, 1 + dfs(r, c - 1, matrix[r][c]));
26+
dp[`${r}|${c}`] = res;
27+
return res;
28+
}
29+
30+
for (var r = 0; r < ROWS; r++) {
31+
for (var c = 0; c < COLS; c++) {
32+
dfs(r, c, -1);
33+
}
34+
}
35+
36+
return Math.max(...Object.values(dp));
37+
}

0 commit comments

Comments
 (0)