Categories
Array Dynamic Programming Leetcode

Minimum Path Sum (Iterative)

let minPathSum = function(grid) {

    if(!grid || !grid.length) return 0;

    let maxRow = grid.length, maxCol = grid[0].length;
    
    for (let row = 0; row < maxRow;row++) {
        for (let col = 0; col < maxCol;col++) {
            console.log(row, col);
            if (row === 0) {
                grid[row][col] = grid[row][col] + (grid[row][col - 1] || 0);
            }
            else if (col === 0) {
                grid[row][col] = grid[row][col] + grid[row - 1][col];
            } else {
                grid[row][col] = Math.min(
                    grid[row][col] + grid[row - 1][col], // top
                    grid[row][col] + grid[row][col - 1] // left
                );
            }
        }
    }
    return grid[maxRow - 1][maxCol - 1];
};

Leave a Reply

Your email address will not be published. Required fields are marked *