LeetCode 329. Longest Increasing Path in a Matrix

231 篇文章 0 订阅

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.

------------------------------------------------------------------------------

Misunderstand first: wrap-around is not allowed, but a cycle a allowed. So up-down dfs:

class Solution:
    def dfs(self, nums, x, y, m, n, seen):
        if ((x, y) in seen):
            return seen[(x, y)]
        res = 1
        for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            nx, ny = x + dx, y + dy
            if (nx >= 0 and nx < m and ny >= 0 and ny < n and nums[nx][ny] > nums[x][y]):
                res = max(res, self.dfs(nums, nx, ny, m, n, seen)+1)
        seen[(x, y)] = res
        return res

    def longestIncreasingPath(self, matrix) -> int:
        m, n = len(matrix), len(matrix[0]) if len(matrix) > 0 else 0
        if (n == 0):
            return 0
        res = 1
        for i in range(m):
            for j in range(n):
                res = max(res, self.dfs(matrix, i, j, m, n, {}))
        return res

Dict with tuple key is too slow, speed up by using List[List]:

class Solution:
    def dfs(self, nums, x, y, m, n, seen):
        if (seen[x][y] > 0):
            return seen[x][y]
        
        res = 1
        for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            nx, ny = x + dx, y + dy
            if (nx >= 0 and nx < m and ny >= 0 and ny < n and nums[nx][ny] > nums[x][y]):
                res = max(res, self.dfs(nums, nx, ny, m, n, seen)+1)
        seen[x][y] = res
        return res

    def longestIncreasingPath(self, matrix) -> int:
        m, n = len(matrix), len(matrix[0]) if len(matrix) > 0 else 0
        if (n == 0):
            return 0
        res = 1
        seen = [[0 for j in range(n)] for i in range(m)]
        for i in range(m):
            for j in range(n):             
                res = max(res, self.dfs(matrix, i, j, m, n, seen))
        return res

 Meanwhile, bottom up DP is also acceptable. Just sort by value first.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值