<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>


class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        M, N = len(grid), len(grid[0])
        q = []
        heapq.heappush(q, (grid[0][0], 0, 0))
        visited = set()
        
        while q:
            dist, i, j = heapq.heappop(q)
            
            # If we've reached the bottom-right corner, return the path sum
            if i == M - 1 and j == N - 1:
                return dist
            
            if (i, j) in visited:
                continue
            visited.add((i, j))
            
            # Explore the cell below
            if i + 1 < M:
                heapq.heappush(q, (dist + grid[i+1][j], i+1, j))
            
            # Explore the cell to the right
            if j + 1 < N:
                heapq.heappush(q, (dist + grid[i][j+1], i, j+1))
        
        # Just in case the grid has some invalid input or unreachable point
        return -1


    # def minPathSum(self, grid: List[List[int]]) -> int:
    #     M, N = len(grid), len(grid[0])
    #     matrix = [[float('inf')] * N for _ in range(M)]
    #     matrix[0][0], q = grid[0][0],[]
    #     heapq.heappush(q,(grid[0][0],0,0))
    #     while(len(q) > 0):
    #         dist,i, j = heapq.heappop(q)
    #         if i == M-1 and j == N-1:
    #             return dist
    #         if (i + 1 < M) and (grid[i+1][j] + dist < matrix[i+1][j]):
    #             matrix[i+1][j] = grid[i+1][j] + dist
    #             heapq.heappush(q,(matrix[i+1][j],i+1, j))
 
    #         if (j + 1 < N) and (grid[i][j+1] + dist < matrix[i][j+1]):
    #             matrix[i][j+1] = grid[i][j+1] + dist
    #             heapq.heappush(q,(matrix[i][j+1], i, j+1))

    #     return matrix[M-1][N-1]
        
21700