Skip to content

Commit 89cff96

Browse files
committed
[leet] 329 Longest Increasing Path in a Matrix (hard)
1 parent 405b19f commit 89cff96

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

허현빈/3주차/260116.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
var longestIncreasingPath = function (matrix) {
2+
const grid = matrix;
3+
let max = 0;
4+
const dir = [
5+
[0, 1],
6+
[0, -1],
7+
[1, 0],
8+
[-1, 0],
9+
];
10+
const set = new Set();
11+
matrix.map((e) => e.map((e2) => set.add(e2)));
12+
const newArr = Array.from(set).sort((a, b) => a - b);
13+
const map = new Map(newArr.map((e, i) => [e, i + 1]));
14+
const backtrackin = (k, row, col) => {
15+
if (k > max) {
16+
max = k;
17+
}
18+
for (let i = 0; i < 4; i++) {
19+
const nx = col + dir[i][1];
20+
const ny = row + dir[i][0];
21+
if (
22+
nx >= 0 &&
23+
ny >= 0 &&
24+
nx < grid[0].length &&
25+
ny < grid.length &&
26+
grid[ny][nx] > grid[row][col]
27+
) {
28+
const val = map.get(grid[ny][nx]);
29+
if (k + newArr.length - val + 1 > max) {
30+
backtrackin(k + 1, ny, nx);
31+
}
32+
}
33+
}
34+
};
35+
for (let i = 0; i < grid.length; i++) {
36+
for (let j = 0; j < grid[0].length; j++) {
37+
backtrackin(1, i, j);
38+
}
39+
}
40+
return max;
41+
};

0 commit comments

Comments
 (0)