# 329. Longest Increasing Path in a Matrix

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* 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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(row * col)******- 空间复杂度: O(row * col)******


我只要能知道从固定一个点出发能得到的最长升序path就可以了，然后遍历每一个点，把这些都记录下来避免重复计算，就是一个简单的记忆化搜索DFS

beats 27.88%

```python
class Solution:  
    def longestIncreasingPath(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: int
        """
        self.dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]]
        row = len(matrix)
        col = len(matrix[0]) if row else 0
        if not row or not col:
            return 0
            
        res, self.cache = 1, {}
        for i in range(row):
            for j in range(col):
                res = max(res, self.helper(matrix, i, j, row, col))
        return res
    
    def helper(self, matrix, i, j, row, col):
        if (i, j) in self.cache:
            return self.cache[(i,j)]
        
        res = 1
        for d in self.dirs:
            next_x, next_y = i + d[0], j + d[1]
            if not (0 <= next_x < row) or not (0 <= next_y < col) or matrix[next_x][next_y] <= matrix[i][j]:
                continue
            res = max(res, 1 + self.helper(matrix, next_x, next_y, row, col))
        self.cache[(i,j)] = res
        return res
```





























