LeetCode 0329. Longest Increasing Path in a Matrix Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0329. Longest Increasing Path in a Matrix

Description

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:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 231 - 1

Solutions

Solution 1: Memoization Search

We design a function dfs(i, j), which represents the length of the longest increasing path that can be obtained starting from the coordinate (i, j) in the matrix. The answer is max_{i, j} dfs(i, j).

The execution logic of the function dfs(i, j) is as follows:

  • If (i, j) has been visited, directly return f(i, j);
  • Otherwise, search (i, j), search the coordinates (x, y) in four directions. If 0 \le x < m, 0 \le y < n and matrix[x][y] > matrix[i][j], then search (x, y). After the search is over, update f(i, j) to f(i, j) = max(f(i, j), f(x, y) + 1). Finally, return f(i, j).

The time complexity is O(m × n), and the space complexity is O(m × n). Where m and n are the number of rows and columns of the matrix, respectively.

Similar problems:

PythonJavaC++GoTypeScript
class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: @cache def dfs(i: int, j: int) -> int: ans = 0 for a, b in pairwise((-1, 0, 1, 0, -1)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]: ans = max(ans, dfs(x, y)) return ans + 1 m, n = len(matrix), len(matrix[0]) return max(dfs(i, j) for i in range(m) for j in range(n))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !