Skip to content

Commit 382c624

Browse files
committed
Minimum Falling Path Sum
1 parent ba31e93 commit 382c624

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

931-minimum-falling-path-sum.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/minimum-falling-path-sum/
3+
4+
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.
5+
A falling path starts at any element in the first row and chooses the element in the next row that
6+
is either directly below or diagonally left/right. Specifically, the next element from position
7+
(row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).
8+
9+
Example 1:
10+
Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
11+
Output: 13
12+
Explanation: There are two falling paths with a minimum sum as shown.
13+
14+
Example 2:
15+
Input: matrix = [[-19,57],[-40,-5]]
16+
Output: -59
17+
Explanation: The falling path with a minimum sum is shown.
18+
19+
Constraints:
20+
n == matrix.length == matrix[i].length
21+
1 <= n <= 100
22+
-100 <= matrix[i][j] <= 100
23+
"""
24+
class Solution:
25+
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
26+
if len(matrix) == 1:
27+
return min(matrix[0])
28+
29+
dp = matrix[0].copy()
30+
min_path = float('inf')
31+
32+
for row in range(1, len(matrix)):
33+
temp = []
34+
for col in range(len(matrix[0])):
35+
min_val = dp[col] + matrix[row][col]
36+
if col - 1 >= 0:
37+
min_val = min(min_val, matrix[row][col] + dp[col-1])
38+
if col + 1 < len(matrix[0]):
39+
min_val = min(min_val, matrix[row][col] + dp[col+1])
40+
41+
temp.append(min_val)
42+
43+
if row == len(matrix) - 1:
44+
min_path = min(min_path, temp[col])
45+
46+
dp = temp
47+
48+
return min_path

0 commit comments

Comments
 (0)