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.