-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path329-longest-increasing-path-in-a-matrix.js
More file actions
75 lines (64 loc) · 1.77 KB
/
329-longest-increasing-path-in-a-matrix.js
File metadata and controls
75 lines (64 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down.
You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]]
Output: 1
*/
/**
* @param {number[][]} matrix
* @return {number}
*/
var longestIncreasingPath = function (matrix) {
if (matrix.length === 0) return 0;
const directions = [
[0, 1], // right
[1, 0], // bottom
[0, -1], // left
[-1, 0], // top
];
const maxRow = matrix.length;
const maxCol = matrix[0].length;
const cache = Array(maxRow)
.fill(0)
.map(() => Array(maxCol).fill(0));
let ans = 0;
const dfs = (matrix, r, c, cache) => {
if (cache[r][c] !== 0) return cache[r][c];
for (let direction of directions) {
const newRow = r + direction[0];
const newCol = c + direction[1];
const rowInBound = 0 <= newRow && newRow < maxRow;
const colInBound = 0 <= newCol && newCol < maxCol;
if (rowInBound && colInBound && matrix[r][c] < matrix[newRow][newCol]) {
cache[r][c] = Math.max(cache[r][c], dfs(matrix, newRow, newCol, cache));
}
}
return ++cache[r][c];
};
for (let r = 0; r < maxRow; r++) {
for (let c = 0; c < maxCol; c++) {
ans = Math.max(ans, dfs(matrix, r, c, cache));
}
}
return ans;
};
const result = longestIncreasingPath([
[9, 9, 4],
[6, 6, 8],
[2, 1, 1],
]);
console.log(result);