Skip to content

Commit 275f002

Browse files
committed
Add solution #329
1 parent d2e28ac commit 275f002

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,7 @@
249249
322|[Coin Change](./0322-coin-change.js)|Medium|
250250
326|[Power of Three](./0326-power-of-three.js)|Easy|
251251
328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium|
252+
329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard|
252253
331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium|
253254
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|
254255
337|[House Robber III](./0337-house-robber-iii.js)|Medium|
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 329. Longest Increasing Path in a Matrix
3+
* https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
4+
* Difficulty: Hard
5+
*
6+
* Given an m x n integers matrix, return the length of the longest increasing path in matrix.
7+
*
8+
* From each cell, you can either move in four directions: left, right, up, or down. You may
9+
* not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
10+
*/
11+
12+
/**
13+
* @param {number[][]} matrix
14+
* @return {number}
15+
*/
16+
var longestIncreasingPath = function(matrix) {
17+
if (!matrix.length) return 0;
18+
const m = matrix.length;
19+
const n = matrix[0].length;
20+
const cache = new Array(m).fill().map(() => new Array(n));
21+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
22+
23+
return Math.max(...new Array(m).fill().map((_, i) =>
24+
new Array(n).fill().map((_, j) => dfs(i, j))).flat());
25+
26+
function dfs(i, j) {
27+
return cache[i][j] || (cache[i][j] = 1 + Math.max(...directions.map(([di, dj]) => {
28+
const [a, b] = [i + di, j + dj];
29+
return a >= 0 && a < m && b >= 0 && b < n && matrix[a][b] > matrix[i][j]
30+
? dfs(a, b) : 0;
31+
})));
32+
}
33+
};

0 commit comments

Comments
 (0)