<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>

<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 &rarr; 3 &rarr; 1 &rarr; 1 &rarr; 1 minimizes the sum.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>

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

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 200</code></li>
	<li><code>0 &lt;= grid[i][j] &lt;= 200</code></li>
</ul>

def memoize(f):
    cache = {}
    def inner(*args):
        if args in cache:
            return cache[args]
        val = f(*args)
        cache[args] = val
        return val
    return inner

def memoize_2d(dim):
    def memoize(f):
        cache = [None] * (dim * dim)
        def inner(x, y):
            # print(x, y)
            idx = x * dim + y
            if cache[idx] is not None:
                # print(x, y, cache[y][x])
                return cache[idx]
            val = f(x, y)
            cache[idx] = val
            return val
        return inner
    return memoize

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        min_path = float('inf')
        n_rows, n_cols = len(grid), len(grid[0])

        @memoize_2d(dim=max(n_rows, n_cols)+1)
        def traverse(x, y):
            if x == n_cols - 1 and y == n_rows - 1:
                return grid[y][x]
            
            if (
                x < 0 or x >= n_cols
                or y < 0 or y >= n_rows
            ):
                return float('inf')
            
            return grid[y][x] + min(
                traverse(x + 1, y),
                traverse(x, y + 1),
            )
        
        return traverse(0, 0)


20700