1
+ """
2
+ Given an m x n integers matrix, return the length of the longest increasing path in matrix.
3
+
4
+ From each cell, you can either move in four directions:
5
+ left, right, up, or down. You may not move diagonally
6
+ or move outside the boundary (i.e., wrap-around is not allowed).
7
+
8
+ Example 1:
9
+ Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
10
+ Output: 4
11
+ Explanation: The longest increasing path is [1, 2, 6, 9].
12
+
13
+ Example 2:
14
+ Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
15
+ Output: 4
16
+ Explanation: The longest increasing path is [3, 4, 5, 6].
17
+ Moving diagonally is not allowed.
18
+
19
+ Example 3:
20
+ Input: matrix = [[1]]
21
+ Output: 1
22
+
23
+
24
+ Constraints:
25
+ (*) m == matrix.length
26
+ (*) n == matrix[i].length
27
+ (*) 1 <= m, n <= 200
28
+ (*) 0 <= matrix[i][j] <= 2^31 - 1
29
+ """
30
+ from typing import List
31
+ import bisect
32
+
33
+ class Solution :
34
+ def longestIncreasingPath (self , matrix : List [List [int ]]) -> int :
35
+ n_rows = len (matrix )
36
+ n_cols = len (matrix [0 ])
37
+
38
+ # sort the entries and store the indexes
39
+ sorted_entries = list ()
40
+ for i in range (n_rows ):
41
+ for j in range (n_cols ):
42
+ bisect .insort (sorted_entries , (matrix [i ][j ], i , j ))
43
+
44
+ longest_path = [[1 ] * n_cols for _ in range (n_rows )]
45
+ max_length = 1
46
+ for val , i , j in sorted_entries :
47
+ length = 0
48
+ if i > 0 and matrix [i - 1 ][j ] < val :
49
+ length = max (length , longest_path [i - 1 ][j ])
50
+ if i + 1 < n_rows and matrix [i + 1 ][j ] < val :
51
+ length = max (length , longest_path [i + 1 ][j ])
52
+ if j > 0 and matrix [i ][j - 1 ] < val :
53
+ length = max (length , longest_path [i ][j - 1 ])
54
+ if j + 1 < n_cols and matrix [i ][j + 1 ] < val :
55
+ length = max (length , longest_path [i ][j + 1 ])
56
+
57
+ longest_path [i ][j ] = length + 1
58
+ max_length = max (max_length , length + 1 )
59
+ return max_length
60
+
61
+
62
+ if __name__ == "__main__" :
63
+ from run_tests import run_tests
64
+
65
+ correct_answers = [
66
+ [[[9 ,9 ,4 ],[6 ,6 ,8 ],[2 ,1 ,1 ]], 4 ],
67
+ [[[3 ,4 ,5 ],[3 ,2 ,6 ],[2 ,2 ,1 ]], 4 ],
68
+ [[[1 ]], 1 ]
69
+ ]
70
+ print (f"Running tests for longestIncreasingPath" )
71
+ run_tests (Solution ().longestIncreasingPath , correct_answers )
0 commit comments