想要看更加舒服的排版、更加准时的推送
关注公众号“不太灵光的程序员”
每日八点有干货推送,微信随时解答你的疑问
困难
深度优先搜索
拓扑排序
记忆化
给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
输入: nums =
[
[9
,9,4],
[6
,6,8],
[2
,1
,1]
]
输出: 4
解释: 最长递增路径为 [1, 2, 6, 9]。
输入: nums =
[
[3
,4
,5
],
[3,2,6
],
[2,2,1]
]
输出: 4
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
从左到右 从上到小遍历
dic 记录已经计算过的点,减少计算次数
from typing import List
# 执行用时:544 ms, 在所有 Python3 提交中击败了64.30%的用户
# 内存消耗:17.4 MB, 在所有 Python3 提交中击败了50.00%的用户
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix: return 0
m = len(matrix)
n = len(matrix[0])
dic = {}
def get_next_node(i, j):
len1 = len2 = len3 = len4 = 1
# 上
if i - 1 >= 0 and matrix[i][j] < matrix[i - 1][j]:
if (i - 1, j) in dic:
len1 = dic[(i - 1, j)]
else:
len1 += get_next_node(i - 1, j)
dic[(i - 1, j)] = len1
# 下
if i + 1 < m and matrix[i][j] < matrix[i + 1][j]:
if (i + 1, j) in dic:
len2 = dic[(i + 1, j)]
else:
len2 += get_next_node(i + 1, j)
dic[(i + 1, j)] = len2
# 左
if j - 1 >= 0 and matrix[i][j] < matrix[i][j - 1]:
if (i, j - 1) in dic:
len3 = dic[(i, j - 1)]
else:
len3 += get_next_node(i, j - 1)
dic[(i, j - 1)] = len3
# 右
if j + 1 < n and matrix[i][j] < matrix[i][j + 1]:
if (i, j + 1) in dic:
len4 = dic[(i, j + 1)]
else:
len4 += get_next_node(i, j + 1)
dic[(i, j + 1)] = len4
return max(len1, len2, len3, len4)
max_len = 0
for i in range(m):
for j in range(n):
lens = get_next_node(i, j)
if lens > max_len:
max_len = lens
return max_len
s = Solution()
nums = [
[3, 4, 5],
[3, 2, 6],
[2, 2, 1]
]
ret = s.longestIncreasingPath(nums)
print(ret, ret == 4)
nums = [[9, 9, 4],
[6, 6, 8],
[2, 1, 1]]
ret = s.longestIncreasingPath(nums)
print(ret, ret == 4)
nums = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[39, 38, 37, 36, 35, 34, 33, 32, 31, 30],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[59, 58, 57, 56, 55, 54, 53, 52, 51, 50],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[79, 78, 77, 76, 75, 74, 73, 72, 71, 70],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[99, 98, 97, 96, 95, 94, 93, 92, 91, 90],
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109],
[119, 118, 117, 116, 115, 114, 113, 112, 111, 110],
[120, 121, 122, 123, 124, 125, 126, 127, 128, 129],
[139, 138, 137, 136, 135, 134, 133, 132, 131, 130],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
ret = s.longestIncreasingPath(nums)
print(ret, ret == 4)