329. Longest Increasing Path in a Matrix

Difficulty:
Related Topics:
Similar Questions:

Problem

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

  Constraints:

Solution

/**
 * @param {number[][]} matrix
 * @return {number}
 */
var longestIncreasingPath = function(matrix) {
    let ylen = matrix.length, xlen = matrix[0].length, ans = 0,
        memo = Array.from({length: ylen}, el => new Uint16Array(xlen))
    const dfs = (y, x) => {
        if (memo[y][x]) return memo[y][x]
        let val = matrix[y][x]
        memo[y][x] = 1 + Math.max(
            y < ylen - 1 && matrix[y+1][x] < val ? dfs(y+1,x) : 0,
            y > 0 && matrix[y-1][x] < val ? dfs(y-1,x) : 0,
            x < xlen - 1 && matrix[y][x+1] < val ? dfs(y,x+1) : 0,
            x > 0 && matrix[y][x-1] < val ? dfs(y,x-1) : 0)
        return memo[y][x]
    }
    for (let i = 0; i < ylen; i++)
        for (let j = 0; j < xlen; j++)
            ans = Math.max(ans, dfs(i, j))
    return ans
};

Explain:

nope.

Complexity: