Minimum Path Sum in TypeScript

function minPathSum(grid: number[][]): number {
    const m = grid.length; // Number of rows
    const n = grid[0].length; // Number of columns
    // Initialize the DP table
    const dp: number[][] = Array.from({ length: m }, () => Array(n).fill(0));

    // Base case: start at the top-left corner
    dp[0][0] = grid[0][0];

    // Fill the first row (can only move right)
    for (let i = 1; i < n; i++) {
        dp[0][i] = dp[0][i - 1] + grid[0][i];
    }

    // Fill the first column (can only move down)
    for (let i = 1; i < m; i++) {
        dp[i][0] = dp[i - 1][0] + grid[i][0];
    }

    // Fill the rest of the DP table
    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            // The value at dp[i][j] is the value in grid[i][j] plus the minimum of
            // the path sums to reach (i-1, j) and (i, j-1)
            dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
        }
    }

    // The optimal solution is in the bottom-right corner of the DP table
    return dp[m - 1][n - 1];
}

PrevNext