Minimum Falling Path Sum II - Problem
Imagine you're a treasure hunter navigating through a dangerous multi-level dungeon! 🏴‍☠️ You have an n x n grid where each cell contains a treasure value (which could be negative - representing traps!). Your goal is to collect treasures by moving from the top row to the bottom row, picking exactly one treasure from each level. Here's the catch: you cannot pick treasures directly below each other - you must shift to a different column in each move. This is called a "falling path with non-zero shifts." Your mission: Find the path that gives you the minimum sum of treasures collected. Example: If you have a 3x3 grid:
[[1,2,3], [4,5,6], [7,8,9]]
One valid path could be: pick 1 (row 0, col 0) → pick 5 (row 1, col 1) → pick 9 (row 2, col 2), giving sum = 15.

Input & Output

example_1.py — Basic 3x3 Grid
$ Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
💡 Note: The minimum falling path is [1,5,9] → but this violates the non-zero shift constraint. Valid paths include [1,4,8]=13, [1,6,7]=14, [2,4,9]=15, [2,6,7]=15, [3,4,8]=15, [3,5,7]=15. The minimum is 13.
example_2.py — Single Element
$ Input: grid = [[7]]
Output: 7
💡 Note: With only one element, there's no choice but to take that element. No shifts are needed since there's only one row.
example_3.py — Negative Values
$ Input: grid = [[-1,2,-3],[4,-5,6],[-7,8,-9]]
Output: -15
💡 Note: Optimal paths include [-3,-5,-7] and [-1,-5,-9], both giving sum -15. The algorithm finds the minimum falling path sum of -15.

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 200
  • -99 ≤ grid[i][j] ≤ 99
  • Non-zero shifts required - cannot pick elements in same column from adjacent rows

Visualization

Tap to expand
Minimum Falling Path Sum II Treasure Hunter Dungeon Navigation INPUT n x n Grid (Dungeon Levels) 1 2 3 Level 0 4 5 6 Level 1 7 8 9 Level 2 grid = [[1,2,3], [4,5,6], [7,8,9]] Rule: Cannot pick same column in consecutive rows! = Treasure = Trap (neg) ALGORITHM STEPS 1 Initialize DP Copy first row as base 2 Track Min Values Find min1, min2 per row 3 Update DP Table Add min from diff column 4 Find Minimum Return min of last row DP Table Evolution: 1 2 3 init 6 6 7 4+2,5+1,6+1 13 14 15 7+6,8+6,9+6 Time: O(n^2) | Space: O(1) FINAL RESULT Optimal Path Visualization 1 2 3 4 5 6 7 8 9 Path: 1 + 5 + 7 = 13 Output: 13 OK Key Insight: For each cell, we only need the minimum and second minimum from the previous row. If current column equals min column, use second min; otherwise use min. This reduces time from O(n^3) to O(n^2) - a crucial optimization for competitive programming! TutorialsPoint - Minimum Falling Path Sum II | Optimal Solution
Asked in
Google 28 Amazon 22 Meta 15 Microsoft 12
38.4K Views
Medium-High Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen