https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
dir = [[-1, 0], [1, 0], [0, 1], [0, -1]]
def dfs(x, y, dp):
if dp[x][y] != -1:
return dp[x][y]
maxLen = 1
for dx, dy in dir:
nx, ny = x + dx, y + dy
if 0<=nx and nx<m and 0<=ny and ny<n and matrix[nx][ny] > matrix[x][y]:
len = 1 + dfs(nx, ny, dp)
maxLen = max(maxLen, len)
dp[x][y] = maxLen
return maxLen
dp = [[-1]*n for _ in range(m)]
ans = 0
for i in range(m):
for j in range(n):
ans = max(ans, dfs(i, j, dp))
return ans
2) 설명