LeetCode 329. Longest Increasing Path in a Matrix

Description

https://leetcode.com/problems/longest-increasing-path-in-a-matrix/

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

Input: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
Output: 4 
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: nums = 
[
  [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.

Explanation

dfs + memorization

Python Solution

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        if not matrix:
            return 0

        
        cache = [[0 for j in range(len(matrix[0]))] for i in range(len(matrix))]
        
        result = 0
        
        
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                result = max(result, self.helper(matrix, i, j, cache))
                
        return result
        
    def helper(self, matrix, i, j, cache):
        directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
        if cache[i][j] != 0:
            return cache[i][j]
        
        for direction in directions:
            x = i + direction[0]
            y = j + direction[1]
            
            if 0 <= x and x < len(matrix) and 0 <= y and y < len(matrix[0]) and matrix[x][y] > matrix[i][j]:
                cache[i][j] = max(cache[i][j], self.helper(matrix, x, y, cache))
        
        cache[i][j] += 1
        
        return cache[i][j]
  • Time Complexity: ~MN
  • Space Complexity: ~MN

Leave a Reply

Your email address will not be published.