<p>Given an <code>n x n</code> array of integers <code>matrix</code>, return <em>the <strong>minimum sum</strong> of any <strong>falling path</strong> through</em> <code>matrix</code>.</p>

<p>A <strong>falling path</strong> starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position <code>(row, col)</code> will be <code>(row + 1, col - 1)</code>, <code>(row + 1, col)</code>, or <code>(row + 1, col + 1)</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg" style="width: 499px; height: 500px;" />
<pre>
<strong>Input:</strong> matrix = [[2,1,3],[6,5,4],[7,8,9]]
<strong>Output:</strong> 13
<strong>Explanation:</strong> There are two falling paths with a minimum sum as shown.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg" style="width: 164px; height: 365px;" />
<pre>
<strong>Input:</strong> matrix = [[-19,57],[-40,-5]]
<strong>Output:</strong> -59
<strong>Explanation:</strong> The falling path with a minimum sum is shown.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == matrix.length == matrix[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 100</code></li>
	<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>
</ul>

from typing import List


class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        n = len(matrix)
        if n == 1:
            return min(matrix[0])
        m = len(matrix[0])
        dp = [[-1 for _ in range(m)] for _ in range(n)]

        def memo(i: int, j: int) -> int:
            if i == n-1:
                return matrix[i][j]
            if dp[i][j] != -1:
                return dp[i][j]
            l = d = r = int(1e9)
            if j - 1 >= 0:
                l = memo(i+1, j-1)
            if j + 1 < m:
                r = memo(i+1, j+1)
            d = memo(i+1, j)
            dp[i][j] = min(l, d, r) + matrix[i][j]
            return dp[i][j]
        # for j in range(m):
        #     memo(0, j)
        # return min(dp[0])

        def tabulation():
            dpp = [[0 for _ in range(m)] for _ in range(n)]
            for j in range(m):
                dpp[0][j] = matrix[0][j]
            for i in range(1, n):
                for j in range(m):
                    l = u = r = int(1e9)
                    if j - 1 >= 0:
                        l = dpp[i-1][j-1]
                    if j + 1 < m:
                        r = dpp[i-1][j+1]
                    u = dpp[i-1][j]
                    dpp[i][j] = min(l, u, r) + matrix[i][j]
            return min(dpp[-1])
        return tabulation()
                        

18400