-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest Increasing Path in a Matrix.py
58 lines (54 loc) · 1.58 KB
/
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
50
51
52
53
54
55
56
57
58
class Node(object):
def __init__(self,x,y,value):
self.x = x
self.y = y
self.v = value
def __cmp__(self,other):
return cmp(self.v, other.v)
def __str__(self):
return str([self.x,self.y,self.v])
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
l = len(matrix)
l2 = len(matrix[0])
s = []
def findNeighbors(node):
X = []
x = node.x
y = node.y
if x-1 >= 0:
X.append(Node(x-1,y,matrix[x-1][y]))
if x<l-1:
X.append(Node(x+1,y,matrix[x+1][y]))
if y>=1:
X.append(Node(x,y-1,matrix[x][y-1]))
if y<l2-1:
X.append(Node(x,y+1,matrix[x][y+1]))
return X
dp = [[1 for i in range(l2)] for j in range(l)]
for i in xrange(l):
for j in xrange(l2):
n = Node(i,j,matrix[i][j])
s.append(n)
s.sort()
highest_in_dp = 1
for i in s:
#print i
#print dp
ns = findNeighbors(i)
highest = 1
for j in ns:
if j<i:
temp=dp[j.x][j.y]+1
if temp > highest:
highest = temp
dp[i.x][i.y] = highest
if highest > highest_in_dp:
highest_in_dp = highest
return highest_in_dp