-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path329.Longest-Increasing-Path-in-a-Matrix.py
49 lines (37 loc) · 1.27 KB
/
329.Longest-Increasing-Path-in-a-Matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
#
# algorithms
# Hard (39.80%)
# Total Accepted: 84,849
# Total Submissions: 213,186
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
row = len(matrix)
if row == 0:
return 0
col = len(matrix[0])
res = [float('-inf')]
dp = [[0] * col for _ in xrange(row)]
def recursive(i, j):
if dp[i][j] > 0:
return dp[i][j]
cur_max = 0
if i > 0 and matrix[i - 1][j] > matrix[i][j]:
cur_max = max(recursive(i - 1, j), cur_max)
if i < row - 1 and matrix[i + 1][j] > matrix[i][j]:
cur_max = max(recursive(i + 1, j), cur_max)
if j > 0 and matrix[i][j - 1] > matrix[i][j]:
cur_max = max(recursive(i, j - 1), cur_max)
if j < col - 1 and matrix[i][j + 1] > matrix[i][j]:
cur_max = max(recursive(i, j + 1), cur_max)
dp[i][j] = cur_max + 1
return dp[i][j]
res = 1
for i in xrange(row):
for j in xrange(col):
res = max(recursive(i, j), res)
return res