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:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9].
Example 2:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
题意:
给一个整数矩阵,找到最长的升序路径,返回其长度
从每个单元格,上下左右四个方向都可以移动,不能对角线或者移动到边界之外
memoization
对函数返回值进行缓存(一种计算机程序优化技术)
思路:
先从最小的开始,四个方向去走,只走升序的,连相等的都不能走
---将矩阵matrix按照值从小到大排序,得到列表slist,
---列表元素(x, y, val)存储原矩阵的(行、列、值)
每个点都记录它能走的最长的路径的长度
---引入辅助数组dp,dp[x][y]表示从矩阵(x, y)元素出发的最长递增路径长度
最后从所有点选出最长的长度
---遍历slist,同时更新(x, y)左、右、上、下四个相邻元素的dp值
参考:
http://bookshadow.com/weblog/2016/01/20/leetcode-longest-increasing-path-matrix/
Python:
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
m=len(matrix)
if m==0:
return 0
n=len(matrix[0])
dp=[[1]*n for i in range(m)]
slist=sorted([(i,j,val)
for i,row in enumerate(matrix)
for j,val in enumerate(row) ],key=operator.itemgetter(2))
for x,y,val in slist:
for dx,dy in zip([1,0,-1,0],[0,1,0,-1]):
nx,ny=x+dx,y+dy
if 0<=nxmatrix[x][y]:
dp[nx][ny]=max(dp[nx][ny],dp[x][y]+1)
return max(max(x) for x in dp)
使用 itemgetter来加速排序,并且可以减少代码的写作难度
import operator
from operator import itemgetter
matrix=[[9,9,4],[6,6,8],[2,1,1]]
# print ((i,j,val) for i, row in enumerate(matrix) for j, val in enumerate(row))
for i, row in enumerate(matrix):
print (i,row)
for j, val in enumerate(row):
print (j,val)
for i, row in enumerate(matrix):
for j, val in enumerate(row):
print (i,j,val)
(0, [9, 9, 4])
(1, [6, 6, 8])
(2, [2, 1, 1])
(0, 2)
(1, 1)
(2, 1)
(0, 0, 9)
(0, 1, 9)
(0, 2, 4)
(1, 0, 6)
(1, 1, 6)
(1, 2, 8)
(2, 0, 2)
(2, 1, 1)
(2, 2, 1)
for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
print (dx,dy)
(1, 0)
(0, 1)
(-1, 0)
(0, -1)