1
1
from typing import List
2
2
3
- class Solution :
4
- def longestIncreasingPath (self , dt : List [List [int ]]) -> int :
5
- dp = [[- 1 for _ in range (len (dt [0 ]))] for _ in range (len (dt ))]
6
-
7
- for sy in range (len (dt )):
8
- for sx in range (len (dt [0 ])):
9
- self .dfs (sy , sx , 1 , dp , dt )
10
-
11
- answer = 0
12
-
13
- for sy in range (len (dt )):
14
- for sx in range (len (dt [0 ])):
15
- answer = max (answer , dp [sy ][sx ])
16
-
17
- return answer
18
-
19
- def dfs (self , sy , sx , depth , dp , dt ):
20
- if dp [sy ][sx ] >= depth :
21
- return
22
3
23
- dp [sy ][sx ] = depth
24
-
25
- dyxs = [(- 1 , 0 ), (0 , 1 ), (1 , 0 ), (0 , - 1 )]
26
- for dyx in dyxs :
27
- dy , dx = dyx
28
- ty = sy + dy
29
- tx = sx + dx
30
-
31
- if self .is_in (ty , tx , dt ):
32
- if dt [sy ][sx ] < dt [ty ][tx ]:
33
- if dp [ty ][tx ] < depth + 1 :
34
- self .dfs (ty , tx , depth + 1 , dp , dt )
35
-
36
-
37
- def is_in (self , idx_row , idx_col , map ):
38
- if (0 <= idx_row < len (map )) and (0 <= idx_col < len (map [0 ])):
39
- return True
40
-
41
- return False
4
+ class Solution :
5
+ def __init__ (self ):
6
+ self .drc = [[- 1 , 0 ], [0 , 1 ], [1 , 0 ], [0 , - 1 ]]
7
+ self .mx_row = 0
8
+ self .mx_col = 0
9
+
10
+ def longestIncreasingPath (self , matrix : List [List [int ]]) -> int :
11
+ self .mx_row = len (matrix )
12
+ self .mx_col = len (matrix [0 ])
13
+ outdegree : List [List [int ]] = [[0 for _ in range (self .mx_col )] for _ in range (self .mx_row )]
14
+ leaves = []
15
+
16
+ for r in range (self .mx_row ):
17
+ for c in range (self .mx_col ):
18
+ for dr , dc in self .drc :
19
+ nr , nc = r + dr , c + dc
20
+ if 0 <= nr < self .mx_row and 0 <= nc < self .mx_col :
21
+ if matrix [nr ][nc ] > matrix [r ][c ]:
22
+ outdegree [r ][c ] += 1
23
+
24
+ if outdegree [r ][c ] == 0 :
25
+ leaves .append ([r , c ])
26
+
27
+ mx = 0
28
+ while len (leaves ) > 0 :
29
+ mx += 1
30
+ newLeaves = []
31
+
32
+ for r , c in leaves :
33
+ for dr , dc in self .drc :
34
+ nr , nc = r + dr , c + dc
35
+ if 0 <= nr < self .mx_row and 0 <= nc < self .mx_col :
36
+ if matrix [nr ][nc ] < matrix [r ][c ]:
37
+ outdegree [nr ][nc ] -= 1
38
+
39
+ if outdegree [nr ][nc ] == 0 :
40
+ newLeaves .append ([nr , nc ])
41
+
42
+ leaves = newLeaves
43
+
44
+ return mx
0 commit comments