Python 0931.py
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
for y in range(len(matrix) - 2, -1, -1):
for x in range(len(matrix[y])):
best = matrix[y+1][x]
if x > 0:
best = min(best, matrix[y+1][x-1])
if x < len(matrix[y]) - 1:
best = min(best, matrix[y+1][x+1])
matrix[y][x] += best
return min(matrix[0])
Difficulty
and has an acceptance rate of about 61% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “minimum falling path sum” problem for a square integer matrix. It works by mutating the input matrix in-place, propagating the optimal sub-path sums from the bottom row upward until the top row contains the cumulative minima. The final answer is the smallest value in the first row.
Core Logic
The algorithm iterates from the second-last row up to the first row. For each cell it determines the smallest reachable value from the row directly below, considering the three possible moves: straight down, down-left, and down-right. The chosen minimum is added to the current cell, turning the cell into the best possible sum for a path that starts at that position.
for y in range(len(matrix) - 2, -1, -1):
for x in range(len(matrix[y])):
best = matrix[y+1][x]
if x > 0:
best = min(best, matrix[y+1][x-1])
if x < len(matrix[y]) - 1:
best = min(best, matrix[y+1][x+1])
matrix[y][x] += best
After the propagation loop finishes, the top row holds the total sums for all possible falling paths that begin at each column. The smallest of these values is the answer:
return min(matrix[0])
Edge Cases Handled
When the current column is at the leftmost edge (x == 0), the algorithm skips the down-left candidate because x > 0 evaluates to false. Similarly, when the column is at the rightmost edge (x == len(matrix[y]) - 1), the down-right candidate is omitted because the condition x < len(matrix[y]) - 1 fails. These guards ensure that the code never attempts to index outside the matrix bounds, correctly handling matrices of any size, including the minimal case of a 1×1 matrix where the loops are bypassed and the single element is returned directly.
Performance Optimizations
The solution achieves optimal runtime by processing each matrix element exactly once. The in-place update eliminates the need for auxiliary storage, reducing memory pressure and avoiding the overhead of copying rows or creating auxiliary DP tables. By reusing the original matrix to store intermediate results, the algorithm benefits from cache locality: each row is accessed sequentially, and the subsequent row is accessed immediately after, which aligns well with typical CPU cache line behavior. The use of simple integer arithmetic and the built-in min function keeps the inner loop lightweight, contributing to fast execution even for large matrices.
ELI5 - Simplified Explanation
Imagine you have a big square grid made of tiles, and each tile has a number written on it. You want to start at the very top row and walk all the way down to the bottom. Each step you take must go to a tile directly below you or a tile that is diagonally underneath you to the left or right. Your goal is to collect the smallest total amount of points by picking the best path as you go.
The code starts from the bottom of the grid and works its way up to the top row. For every tile in a row, the code looks at the three tiles right underneath it in the next row down. It picks the smallest neighbor, adds that number to the number on the current tile, and saves the new total right there. By the time the computer reaches the very top row, every tile now holds the value of the best possible path starting from that specific spot. Once the work is done, the computer looks at all the numbers in that top row and chooses the smallest one to find the best way to travel down the whole grid.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| martianoff | Scala | ||||||||
| shreymehul | C# | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| martianoff | Scala | ||||||||
| shreymehul | C# | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1289: Minimum Falling Path Sum II
Solved On The Same Day
- problem 71: Simplify Path
- problem 309: Best Time to Buy and Sell Stock with Cooldown
- problem 516: Longest Palindromic Subsequence
- problem 673: Number of Longest Increasing Subsequence
- problem 712: Minimum ASCII Delete Sum for Two Strings
- problem 714: Best Time to Buy and Sell Stock with Transaction Fee
- problem 740: Delete and Earn
- problem 2483: Minimum Penalty for a Shop
- problem 188: Best Time to Buy and Sell Stock IV
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality