Skip to content

Commit d533ce3

Browse files
committed
Added Python solution for "Longest Increasing Path in a Matrix"
1 parent 5c52109 commit d533ce3

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from functools import lru_cache
2+
from typing import List
3+
4+
5+
class Solution:
6+
"""
7+
Time: O(n*m)
8+
Memory: O(n*m)
9+
"""
10+
11+
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
12+
@lru_cache(maxsize=None)
13+
def max_path(i: int, j: int) -> int:
14+
val = matrix[i][j]
15+
return 1 + max(
16+
max_path(i + 1, j) if i + 1 < n and val < matrix[i + 1][j] else 0,
17+
max_path(i - 1, j) if i > 0 and val < matrix[i - 1][j] else 0,
18+
max_path(i, j + 1) if j + 1 < m and val < matrix[i][j + 1] else 0,
19+
max_path(i, j - 1) if j > 0 and val < matrix[i][j - 1] else 0,
20+
)
21+
22+
n, m = len(matrix), len(matrix[0])
23+
return max(max_path(row, col) for row in range(n) for col in range(m))

Python/Spiral Matrix.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
Time: O(?)
7+
Memory: O(?)
8+
"""
9+
10+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
11+
if not matrix:
12+
return []
13+
return matrix.pop(0) + self.spiralOrder(list(map(list, zip(*matrix)))[::-1])
0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)