【LEETCODE】329-Longest Increasing Path in a Matrix [Python]

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<=nx<m and 0<=ny<n and matrix[nx][ny]>matrix[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

python enumerate函数用法

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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值