Minimum Falling Path Sum II — LeetCode 1289 Python Solution
- Problem
- #1289
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.
Example
- Input
- grid = [[1,2,3],[4,5,6],[7,8,9]]
- Output
- 13
- Explanation
- The possible falling paths are:
Python solution
class Solution:
def minFallingPathSum(self, grid: List[List[int]]) -> int:
n = len(grid)
f = [0] * n
for row in grid:
g = row[:]
for i in range(n):
g[i] += min((f[j] for j in range(n) if j != i), default=0)
f = g
return min(f)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^3) |
| Space | O(n^2) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1289. Minimum Falling Path Sum II is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1289. Minimum Falling Path Sum II?
- LeetCode 1289. Minimum Falling Path Sum II is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1289. Minimum Falling Path Sum II?
- The Python solution on this page runs in O(n^3).
- What is the space complexity of LeetCode 1289. Minimum Falling Path Sum II?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 1289. Minimum Falling Path Sum II cover?
- LeetCode 1289. Minimum Falling Path Sum II is tagged Array, Dynamic Programming and Matrix on LeetCode.