329. Longest Increasing Path in a Matrix
Leetcode
題目
解答
var longestIncreasingPath = function(matrix) {
const m = matrix.length;
const n = matrix[0].length;
const dir = [
{row: -1, col: 0},
{row: 0, col: 1},
{row: 1, col: 0},
{row: 0, col: -1}
]
const dfs = (row, col) => {
let max = 1;
for (let i=0; i<dir.length; i++) {
const nextRow = row+dir[i].row;
const nextCol = col+dir[i].col;
// 邊界條件
if (
nextRow < 0 ||
nextRow >= m ||
nextCol < 0 ||
nextCol >= n ||
matrix[nextRow][nextCol] <= matrix[row][col]
) continue;
max = Math.max(max, dfs(nextRow, nextCol) + 1)
}
return max;
}
let res = 1;
for (let row=0; row<m; row++) {
for (let col=0; col<n; col++) {
res = Math.max(res, dfs(row, col));
}
}
return res;
};測資
參考資料
Last updated