-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path931.py
More file actions
35 lines (32 loc) · 1.01 KB
/
Copy path931.py
File metadata and controls
35 lines (32 loc) · 1.01 KB
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
'''
Time-O(nxn)
Space-O(nxn)
'''
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
return self.mindp(matrix)
def mindp(self, matrix):
n = len(matrix)
dp = [[0]*n for _ in range(n)]
for i in range(n):
dp[0][i] = matrix[0][i]
for i in range(1, n):
for j in range(n):
if j == 0:
dp[i][j] = min(
dp[i-1][j] + matrix[i][j],
dp[i-1][j+1] + matrix[i][j]
)
continue
if j == n - 1:
dp[i][j] = min(
dp[i-1][j] + matrix[i][j],
dp[i-1][j-1] + matrix[i][j]
)
continue
dp[i][j] = min(
dp[i-1][j-1] + matrix[i][j],
dp[i-1][j] + matrix[i][j],
dp[i-1][j+1] + matrix[i][j],
)
return min(dp[n-1])